Showing posts with label SQL Query Logics. Show all posts
Showing posts with label SQL Query Logics. Show all posts

Wednesday, October 24, 2012

MySQL Date Functions

Working with date in MySQL is very important for date based query processing. today we going to get some important MySQL date functions frequently used in projects.

Here is the date functions with example queries from Article table  have the column date_of_post

CURDATE() - Return the current date

Example:

SELECT * FROM articles WHERE date_of_post = CURDATE()

 

DAY()   - Return day number from the date column

Example:
SELECT * FROM article WHERE DAY(date_of_post) = 1

 

MONTH() - Return Month number from the date column

Example:
SELECT * FROM article WHERE MONTH(date_of_post) = 2

 

YEAR() – Return year number from the date column

Example:
SELECT * FROM article WHERE MONTH(date_of_post) = 2011

 

LAST_DAY() -  Return Last date as number, From the month of the date column

Example:
SELECT * FROM article WHERE DAY(date_of_post) = LAST_DAY(date_of_post)

 

DAYNAME() - Return day name as string from the date column

SELECT DAYNAME (date_of_post) AS `day_of_post` FROM article

 

MONTHNAME() - Return Month name as string from date column

Example:
SELECT MONTHNAME(date_of_post) as `month_of_post` FROM article

 

QUARTER() - Return Quarter Number as 1 to 4 Format as number

Example:
SELECT QUARTER(date_of_post) AS `post_quarter` FROM article

 

WEEK() - Return Week Number Number (0-53)

Example:
SELECT WEEK(date_of_post) AS `week ` FROM article

Saturday, January 28, 2012

Find the Second largest value from MySql, MsSql, Sql Server table


Finding Second Bigger or largest value from the table column in MySQL / MS SQL / SQLServer, here is the simple sql query to identify the Second toppest value from database table.

Using MAX(fieldname) function

salary_master: (Sample Data)

id     name        salary
1      AAA         20000
2      BBB         18000
3      CCC         19000

SELECT MAX(salary) from salary_master 
above Query will return output (Eg: 20000) the first largest or biggest value from table column.
Using SubQuery we will extract the less than maximum value data and than find the MAX
below the code which get the Maximum salary from salary_master table which was less than the maximum salary (ie., return records except 20000)
SELECT * from salary_master 
where salary < (SELECT MAX(salary) from salary_master)

Output:
id     name        salary
2      BBB         18000
3      CCC         19000



Now will process the MAX(salary) instead of * we will get the output Second Largest Value

SELECT MAX(salary) from salary_master 
where salary < (SELECT MAX(salary) from salary_master)

Output:
20000