Uploaded by John Gorgy

lecture notes functions

advertisement
SQL Functions
Lets try a few of them and see how they work. Lets create a table and name is as orders. Add a
few fields - id, orderdate, orderprice, customer_fname, customer_lname.
id - PK - data type - INT
orderdate - data type - date
orderprice - data type – Decimal – length/values – 6,2
customer_fname - data type – Text
customer_lname - data type - Text
Now lets add a few records. Please remember the format for date is YYYY-MM-DD. Orderprice
field takes only numbers and customer takes only text.
Please note – in Decimal – Length-Values – 6.2. – 6 is the first set before the decimal point and
2 is the after the decimal point.
AVG() - returns the averate value of a numeric column
SELECT AVG(orderprice) AS orderaverage FROM orders
COUNT() - returns the number of rows that matches a specified criteria
SELECT COUNT(customer_fname) from orders
Another one - SELECT COUNT(customer_fname) AS customer FROM orders WHERE
customer_fname = 'Jane'
Please note, we have single quotes around ‘Jane’. If you copy and paste from MS word, it may
work because of the quotes.
If you want to count the number of unique customers in your orders table then try the following:
SELECT COUNT(DISTINCT customer_fname) AS customername FROM orders
MAX() - returns the largest value of the selected column
SELECT MAX(orderprice) AS maxorderprice FROM orders
MIN() - returns the smallest value of the selected column
SELECT MIN(orderprice) AS smallestorderprice FROM orders
SUM() - returns the total sum of a numeric column
SELECT SUM(orderprice) AS ordertotal FROM orders
Group BY - used in conjunction with the aggregate functions to group the result set by one or
more columns
Let's say we duplicate orders from a few customers in our table and the goal is to group them
together.
SELECT customer_fname,SUM(orderprice) FROM orders
GROUP BY customer_fname
ROUND() - is used to round a numeric field to the number of decimals specified.
SELECT customer_fname, ROUND(orderprice,0) as orderprice FROM orders
NOW() - returns the current system date and time
SELECT customer_fname, orderprice, Now() as curerntdate FROM orders
Date Search
Let's say you want to find out all the orders received after a certain date. Then try the following:
SELECT customer_fname, orderprice, orderdate FROM orders WHERE orderdate > '2011-2-10'
Note, make sure to use single quotes around date
Download