You are on page 1of 14

SQL Basic Commands

Name some database system where SQL is used

MySQL, SQL Server, Access, Oracle, Sybase, DB2

To select all columns from a table (Customers) for rows where the Last_Name column
has Smith

SELECT * FROM Customers WHERE Last_Name='Smith';

To return only the Cust_No and First_Name where the Last_Name column has Smith

SELECT Cust_No, First_Name FROM Customers WHERE Last_Name='Smith';

To select the First_Name and Nickname columns from the Friends table for rows in which


the Nicknamecolumn contains the string "brain", use this statement:

SELECT First_Name, Nickname FROM Friends WHERE Nickname LIKE '%brain%';

 To query the same table, retrieving all columns for rows in which
the First_Name column's value begins with any letter and ends with "en", use this
statement:

SELECT * FROM Friends WHERE First_Name LIKE '_en';

The result set might look like:

+------------+------------+-----------+

| First_Name | Last_Name | Nickname |

+------------+------------+-----------+

| Ben | Smith | Brainiac |

| Jen | Peters | Sweetpea |

+------------+------------+-----------+

2 rows in set (0.03 sec)

 If you used the % wild card instead (e.g., '%en') in the example above, the result set
might look like:
 +------------+------------+-----------+

 | First_Name | Last_Name | Nickname |

 +------------+------------+-----------+

 | Ben | Smith | Brainiac |

 | Glen | Jones | Peabrain |

 | Jen | Peters | Sweetpea |

 | Steven | Griffin | Nobrainer |

 +------------+------------+-----------+

4 rows in set (0.05 sec)

The following SQL statement selects all customers from the country "Germany" AND the
city "Berlin", in the "Customers" table:

Example

SELECT * FROM Customers


WHERE Country='Germany'
AND City='Berlin';

OR Operator Example

The following SQL statement selects all customers from the city "Berlin" OR "München", in the
"Customers" table: 

Example

SELECT * FROM Customers


WHERE City='Berlin'
OR City='München';

Combining AND & OR

You can also combine AND and OR (use parenthesis to form complex expressions).

The following SQL statement selects all customers from the country "Germany" AND the city
must be equal to "Berlin" OR "München", in the "Customers" table:
Example

SELECT * FROM Customers


WHERE Country='Germany'
AND (City='Berlin' OR City='München');

selects all customers with a City of "Paris" or "London":

SELECT * FROM Customers


WHERE City IN ('Paris','London');

Alter Table syntax

ALTER TABLE table_name


ADD column_name datatype

Add a column named "DateOfBirth" in the "Persons" table.

ALTER TABLE Persons


ADD DateOfBirth date

To delete the column named "DateOfBirth" in the "Persons" table.

ALTER TABLE Persons


DROP COLUMN DateOfBirth

Using function

1.Find the average salary of instructor in computer science department with title avg_salary

Select avg(salary) as avg_salary


From employee
Where dept_ name = ‘cpmp_sci’;

2. Find no.of tuples from employee releation

Select count(*)
From course;

Advanced SQL Commands

Grouping data from table in SQL

1. Find average salary from each department


Select dept_name avg(salary) as avg_salary
From employee
Group by dept_name;

2. Display only those department where average salary of the employee is more than 60,000

Select dept_name. avg(salary) as avg_salary


From employee
Gropup by dept_name
Having avg(salary)> 60000;

3. Find out how many employees in each branch

Table Emp_Mstr(Branch_no, Emp_no) branch_no start with B and Emp_no strat with
E e.g. B1 as branch no and E1 as employee number

Select branch-no “branch no”, count(emp_no)


From Emp-Mstr
Group by Branch_no;

4. Find out the total number of accounts by each employee

Table ACCT-MSTR(emp_no, acct_no) (Start employee no. with E e.g. E1)

Select emp_no count(Acc-no)


From acc_mstr
Group by emp_no;

5. Find out the total number accouts segregated on the basis of account type per branch
Table ACCT_MSTR(branch-no, type , acct_no) A/C type is either CA OR SB

select branch_no, type, count(acc_no)


from acc_mstr group by branch_no.type;

6. Find out customer having more than one account


Table customer(cust-no, acct_fd_no) Start customer number with “C” e.g. C1

Select cust_no, count(acct_fd_no)


Where acct_fd_no like ‘CA%’ OR acct_fd_no like ‘SB%’
Group by cust_no having count(acct_fd_no)>1;
SUBQUERIES

1. Retrieve the address of customer named”Amit Shah”


Table cust_mstr(cust_no, fname,lname)
Addr_dtls(cobe_no,add1,add2,city,state,pincode)
Slelect code_no”cust NO.”,ADDR1 ||’ ‘||ADDR2||’’|| CITY ||’,’||STATE ||’,’||PINCODE
“ADDRESS”
FROM ADR_DTLS WHERE CODE_NO IN(SELECT CUST_NO FROM
CUST_MSTR
WHERE FNAME = ‘Amit’ and lname =’shah’;
2. Create tables car (id, name(car name). cost) customer(id,name) reservation (id,
customerid, date)
Examples of three tables
Car table
mysql> SELECT * FROM Cars;
+----+------------+--------+
| Id | Name | Cost |
+----+------------+--------+
| 1 | Audi | 52642 |
| 2 | Mercedes | 57127 |
| 3 | Skoda | 9000 |
| 4 | Volvo | 29000 |
| 5 | Bentley | 350000 |
| 6 | Citroen | 21000 |
| 7 | Hummer | 41400 |
| 8 | Volkswagen | 21600 |
+----+------------+--------

mysql> SELECT * FROM Customers; SELECT * FROM Reservations;


Customer tabel
+------------+-------------+
| CustomerId | Name |
+------------+-------------+
| 1 | Paul Novak |
| 2 | Terry Neils |
| 3 | Jack Fonda |
| 4 | Tom Willis |
+------------+-------------+

Reservation table

Id | CustomerId | Day |
+----+------------+------------+
| 1 | 1 | 2009-11-22 |
| 2 | 2 | 2009-11-28 |
| 3 | 2 | 2009-11-29 |
| 4 | 1 | 2009-11-29 |
| 5 | 3 | 2009-12-02 |
+----+------------+------------+

Subquery with the INSERT statement

3. create a copy of the Cars table. Into another table called Cars2

mysql> CREATE TABLE Cars2(Id INT NOT NULL PRIMARY KEY,


-> Name VARCHAR(50) NOT NULL, Cost INT NOT NULL);

Scalar subqueries

4. Display the name of the customer from the Customers table, whose reservation has Id
equal to 5 in the Reservations table
mysql> SELECT Name FROM Customers WHERE
-> CustomerId=(SELECT CustomerId FROM Reservations WHERE Id=5);

Table subqueries

5. Display the names of the customers, who made some reservations.


mysql> SELECT Name FROM Customers WHERE CustomerId IN
-> (SELECT DISTINCT CustomerId FROM Reservations);

6. Display all cars that cost below the average price of all cars in the table.

mysql> SELECT Name FROM Cars WHERE Cost <


-> (SELECT AVG(Cost) FROM Cars);

7. MySQL subquery within a WHERE clause


Display the customer who has the maximum payment. Customer(cust_id, cust_name,
payment)
SELECT customerNumber,
checkNumber, amount
form payments
WHERE amount = (
SELECT MAX(amount)
FROM payments
);

Stored Procedure

1. Write stored procedure to display the content of product table Product(prod_id,


prod_name, prod_price)
mysql>DELIMITER //
mysql>CREATE PROCEDURE GetAllProducts()
   BEGIN
   SELECT *  FROM products;
   END //
mysql>DELIMITER ;

To call procedure
mysql> call GetAllProduct();

2. Write stored procedure to Display message “WELCOME to mysql”

mysql>DELIMITER //
mysql>CREATE PROCEDURE dispmeaasge()
   BEGIN
   SELECT ‘WELCOME TO MYSQL’;
   END //
mysql>DELIMITER ;

To call procedure
mysql> call dispmeassaget();

Example of IN parameter

3. Create table offices(company_name, add1, add2, country) insert 5 records with different
country name such as USA, UK. Japan, India etc
Write procedure to display company name for specific country given by user

mysql>DELIMITER //
mysq>CREATE PROCEDURE GetOfficeByCountry(IN countryName VARCHAR(25))
BEGIN
SELECT *
FROM offices
WHERE country = countryName;
END //

mysql> DELIMITER ;

mysql> CALL GetOfficeByCountry('USA');

Example of OUT parameter

4. Create table orders(orderNumber, prod_name, prod_price, status) Status will be either


pending or shipped.
Write procedure to find total number of orders depending upon status (either shipped or
pending )given by user

mysql>DELIMITER $$
mysql>CREATE PROCEDURE CountOrderByStatus(IN orderStatus VARCHAR(25),
OUT total INT)
BEGIN
SELECT count(orderNumber) INTO total
FROM orders
WHERE status = orderStatus;
END $$

mysql>DELIMITER ;
mysql>CALL CountOrderByStatus('Shipped',@total);
 
mysql>SELECT @total;

Example of IN and OUT parameter

5. create table administrator1( capital double, rate int(5), duration int(3),interest


double(10,2))
Write procedure to calculate interest and store it in file

mysql>DELIMITER $$
mysql>CREATE
PROCEDURE `test2`(IN capital DOUBLE , IN rate INT , IN duration INT , OUT interest
DOUBLE)
BEGIN
SET interest = (capital * rate * duration)/100;
INSERT INTO `administrator1`(`interest`) VALUES(interest);
END $$

mysql>DELIMITER ;
mysql> call test2(100 , 7 , 3 , @primary_interest);
mysql> select @primary_interest;
+-------------------+
| @primary_interest |
+-------------------+
| 21 |
+-------------------+
1 row in set (0.00 sec)

mysql> select *
-> from administrator1;
+---------+------+----------+----------+
| capital | rate | duration | interest |
+---------+------+----------+----------+
| NULL | NULL | NULL | 21.00 |
+---------+------+----------+----------+
1 row in set (0.00 sec)

Example of INOUT parameter

6. Write procedure to change value of counter using INOUT parameter

mysql> DELIMITER $$
mysql> CREATE PROCEDURE set_counter(INOUT count INT(4),IN inc INT(4))
BEGIN
SET count = count + inc;
END$$
mysql> DELIMITER ;

mysql> SET @counter = 1;


mysql> CALL set_counter(@counter,1); -- 2
mysql> CALL set_counter(@counter,1); -- 3
mysql> CALL set_counter(@counter,5); -- 8
mysql> SELECT @counter;

Exercise: Stored procedure


1.Create table of employee(emp_id, emp_name, dept_id, salary)
mysql> select * from employee;
+--------+----------+---------+--------+
| emp_id | emp_name | dept_id | salary |
+--------+----------+---------+--------+
|    103 | Jack     |       1 |   1400 |
|    104 | John     |       2 |   1450 |
|    108 | Alan     |       3 |   1150 |
|    107 | Ram      |    NULL |    600 |
+--------+----------+---------+--------+

To find out total number of employee by department, dept_id 


mysql> DELIMITER //
mysql> create procedure usp_totalEmployeeByDeparment(IN id INT)
    -> begin
    -> select count(*) as total from employee where dept_id = id;
    -> end//
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER ;
sql> call usp_totalEmployeeByDeparment(2);
+-------+
| total |
+-------+
|     1 |
+-------+

2. Display name of the employee whose id given by you


mysql> DELIMITER  //
mysql> create procedure usp_GetEmployeeName(IN id INT, OUT name VARCHAR(20)
)
    -> begin
    -> select emp_name into name from employee where emp_id = id;
    -> end //
Query OK, 0 rows affected (0.52 sec)
mysql> DELIMITER ;

mysql> call usp_GetEmployeeName(103, @name);
Query OK, 1 row affected (0.05 sec)

Calling stored procedure from MySQL command line:

mysql> select @name;
+-------+
| @name |
+-------+
| Jack  |

 3. Stored procedure that accepts two parameters, adds them up and returns the result in OUT
parameter total.

mysql>DELIMITER $$
mysql>CREATE PROCEDURE mysum(IN par1 decimal(20,2),
                                 IN par2 decimal(20,2),
         OUT total decimal(20,2))
BEGIN
    SET total = par1 + par2;
END $$

mysql>DELIMITER ;
mysql>Call mysum(10.5,25,@total);
mysql>select @total as t;

4. Stored procedure with function


Create table product(pro_no, Prod_name, prod_price(8,2)

mysql>CREATE PROCEDURE productpricing(


OUT pl DECIMAL(8,2),
OUT ph DECIMAL(8,2),
OUT pa DECIMAL(8,2)
)
BEGIN
SELECT Min(prod_price)
INTO pl
FROM products;
SELECT Max(prod_price)
INTO ph
FROM products;
SELECT Avg(prod_price)
INTO pa
FROM products;
END;
Note: Parameter Datatypes The datatypes allowed in stored procedure parameters are the
same as those used in tables.
Note that a recordset is not an allowed type, and so multiple rows and columns could not be
returned via a parameter. This is why three parameters (and three SELECT statements) are
used in the previous example.

Mysql> CALL productpricing(@pricelow, @pricehigh, @priceaverage);


To obtain all three values, you can use the following:
Mysql> SELECT @pricehigh, @pricelow, @priceaverage;

5. Accepts an order number and returns the total for that order: orderitems(order_num,
Item_name, item_price, Quantity)
CREATE PROCEDURE ordertotal(
IN onumber INT,
OUT ototal DECIMAL(8,2)
)
BEGIN
SELECT Sum(item_price*quantity)
FROM orderitems
WHERE order_num = onumber
INTO ototal;
END;
To invoke this new stored procedure you can use the following:
Mysql> CALL ordertotal(20005, @total);
SELECT @total;

6. For question no. 5 write procedure for following


 Obtain the total (as before).
 Conditionally add tax to the total. (only for some customers) Tax rate is 6% by default
 Return the total (with or without tax).
-- Name: ordertotal
-- Parameters: onumber = order number
-- taxable = 0 if not taxable, 1 if taxable
-- ototal = order total variable
CREATE PROCEDURE ordertotal(
IN onumber INT,
IN taxable BOOLEAN,
OUT ototal DECIMAL(8,2)
) COMMENT 'Obtain order total, optionally adding tax'
BEGIN
-- Declare variable for total
DECLARE total DECIMAL(8,2);
-- Declare tax percentage
DECLARE taxrate INT DEFAULT 6;
-- Get the order total
SELECT Sum(item_price*quantity)
FROM orderitems
WHERE order_num = onumber
INTO total;
-- Is this taxable?
IF taxable THEN
-- Yes, so add taxrate to the total
SELECT total+(total/100*taxrate) INTO total;
END IF;
-- And finally, save to out variable
SELECT total INTO ototal;
END;
CALL ordertotal(20005, 1, @total);
SELECT @total;

You might also like