SlideShare a Scribd company logo
Useful Date, Number and String SQL Queries
Geta sequence ofnumbers(1-12) in a table:
We can generate sequence of numbersusingthe connectbyexpression..We canspecifythe upperlimit
inthe level condition.
SELECT ROWNUMMNTH FROMDUAL CONNECTBY LEVEL <= 12
GetWeekenddatesbetweentwoinput dates:
selectdtdate,to_char(to_date(dt),'DY') day
from(selecttrunc(to_date(:DATE_FROM)) +level - 1dt fromdual
connectby trunc(to_date(:DATE_FROM))+level - 1 <= trunc(to_date(:DATE_TO)))
where to_char(to_date(dt),'DY') in('SAT','SUN')
Generate Random numberin SQL query:
selecttrunc(DBMS_RANDOM.value(100,999)) fromdual
SELECT ROUND(DBMS_RANDOM.VALUE() * 100) + 1 ASrandom_numFROMDUAL
ConvertingComma Separated ValuesintoTable:
The querycan come quite handywhenyouhave commaseparateddatastringthat youneedto convert
intotable sothat you can use otherSQL querieslike IN orNOTIN.
Here we are converting'AA,BB,CC,DD,EE,FF'stringtotable containingAA,BB,CCetc.as eachrow.
Once you have thistable youcan joinitwithothertable to quicklydosome useful stuffs.
WITH csv AS (SELECT 'AA,BB,CC,DD,EE,FF'AScsvdataFROMDUAL)
SELECT REGEXP_SUBSTR (csv.csvdata,'[^,]+',1, LEVEL) pivot_char
FROMDUAL, csv
CONNECTBY REGEXP_SUBSTR (csv.csvdata,'[^,]+',1,LEVEL) IS NOT NULL
WITH DATA AS( SELECT 'word1,word2, word3,word4, word5,word6' str FROM dual)
SELECT TRIM(regexp_substr(str,'[^,]+',1, LEVEL)) str
FROMDATA CONNECTBY instr(str,',',1, LEVEL - 1) > 0
ConvertingNumberinto Word:
SELECT TO_CHAR(TO_DATE (1526, 'j'), 'jsp') FROMDUAL
Getthe first day of the month:
Quicklyreturnsthe firstdayof current month.Insteadof currentmonthyou wantto findfirstdayof
monthwhere a date falls,replace SYSDATEwithany date column/value.
SELECT TRUNC (SYSDATE,'MONTH') "Firstday of current month"FROMDUAL
Getthe last day of the month:
Thisqueryis similartoabove butreturnslastday of current month.
One thingworthnotingisthat it automaticallytakescare of leapyear.
So if youhave 29 daysinFeb,it will return29/2.
If you wantto findthe last dayof a monthotherthan the current month,replace SYSDATEwithanydate
column/value.
SELECT TRUNC (LAST_DAY(SYSDATE)) "Lastday of current month"FROMDUAL
Getthe first day of the Year:
Firstday of year isalways1-Jan.This querycan be use instoredprocedure where youquicklywantfirst
day of year forsome calculation.
SELECT TRUNC (SYSDATE,'YEAR') "YearFirst Day"FROM DUAL
Getthe last day of the year:
SELECT ADD_MONTHS(TRUNC (SYSDATE,'YEAR'), 12) - 1 "Year Last Day" FROMDUAL
Getnumber ofdays in current month:
Thisqueryreturnsnumberof days incurrentmonth.You can change SYSDATEwithany date/value to
knownumberof daysin that month.
SELECT CAST(TO_CHAR(LAST_DAY (SYSDATE),'dd') ASINT) number_of_daysFROMDUAL
Getnumber ofdays leftin current month:
Belowquerycalculatesnumberof daysleftincurrentmonth
SELECT SYSDATE,LAST_DAY (SYSDATE) "Last",LAST_DAY (SYSDATE) - SYSDATE "Days left"FROMDUAL
Getnumber ofdays betweentwodates:
Use thisqueryto getdifference betweentwodatesinnumberof days
SELECT TRUNC(sysdate) - TRUNC(e.original_date_of_hire) FROMper_periods_of_service
Display each monthsstart and enddate upto last month of the year:
Thisquerydisplaysstartdate and enddate of eachmonthin currentyear.You mightwantto use thisfor
certaintypesof calculations.
SELECT ADD_MONTHS(TRUNC (SYSDATE,'MONTH'), i) start_date,TRUNC (LAST_DAY(ADD_MONTHS
(SYSDATE,i))) end_date
FROMXMLTABLE ('for$i in 0 toxs:int(D) return$i'
PASSINGXMLELEMENT (d,FLOOR (MONTHS_BETWEEN (ADD_MONTHS(TRUNC (SYSDATE,'YEAR') - 1,
12),SYSDATE)))
COLUMNS i INTEGER PATH '.')
Getnumber ofseconds passedsince today (since 00:00 hr):
SELECT (SYSDATE- TRUNC (SYSDATE)) *24 * 60 * 60 num_of_sec_since_morningFROMDUAL
Getnumber ofseconds lefttoday (till 23:59:59 hr):
SELECT (TRUNC(SYSDATE+1) - SYSDATE) * 24 * 60 * 60 num_of_sec_leftFROMDUAL
GetMonth Namesin a year:
selectto_char(add_months(sysdate,LEVEL),'MON') SEQUENCE,
substr(to_char(add_months(sysdate,LEVEL),'DD-MON-YY','nls_date_language=english'),4,3)
MONTH fromdual
CONNECTBY LEVEL <= 12
orderby SEQUENCE ASC
Hope thishelps..
Keepfollowingformore updates.

More Related Content

What's hot

11. Linear Models
11. Linear Models11. Linear Models
11. Linear Models
FAO
 
Create a correlation plot from joined tables and lag times
Create a correlation plot from joined tables and lag timesCreate a correlation plot from joined tables and lag times
Create a correlation plot from joined tables and lag times
DougLoqa
 
13. Cubist
13. Cubist13. Cubist
13. Cubist
FAO
 
Data warehouse 21 other varients of star schema
Data warehouse 21 other varients of star schemaData warehouse 21 other varients of star schema
Data warehouse 21 other varients of star schema
Vaibhav Khanna
 
Manipulating data with dates
Manipulating data with datesManipulating data with dates
Manipulating data with dates
Rupak Roy
 
8. R Graphics with R
8. R Graphics with R8. R Graphics with R
8. R Graphics with R
FAO
 
Applied numerical methods lec1
Applied numerical methods lec1Applied numerical methods lec1
Applied numerical methods lec1
Yasser Ahmed
 
Data import-cheatsheet
Data import-cheatsheetData import-cheatsheet
Data import-cheatsheet
Dieudonne Nahigombeye
 
"Principal Component Analysis - the original paper" presentation @ Papers We ...
"Principal Component Analysis - the original paper" presentation @ Papers We ..."Principal Component Analysis - the original paper" presentation @ Papers We ...
"Principal Component Analysis - the original paper" presentation @ Papers We ...
Adrian Florea
 

What's hot (9)

11. Linear Models
11. Linear Models11. Linear Models
11. Linear Models
 
Create a correlation plot from joined tables and lag times
Create a correlation plot from joined tables and lag timesCreate a correlation plot from joined tables and lag times
Create a correlation plot from joined tables and lag times
 
13. Cubist
13. Cubist13. Cubist
13. Cubist
 
Data warehouse 21 other varients of star schema
Data warehouse 21 other varients of star schemaData warehouse 21 other varients of star schema
Data warehouse 21 other varients of star schema
 
Manipulating data with dates
Manipulating data with datesManipulating data with dates
Manipulating data with dates
 
8. R Graphics with R
8. R Graphics with R8. R Graphics with R
8. R Graphics with R
 
Applied numerical methods lec1
Applied numerical methods lec1Applied numerical methods lec1
Applied numerical methods lec1
 
Data import-cheatsheet
Data import-cheatsheetData import-cheatsheet
Data import-cheatsheet
 
"Principal Component Analysis - the original paper" presentation @ Papers We ...
"Principal Component Analysis - the original paper" presentation @ Papers We ..."Principal Component Analysis - the original paper" presentation @ Papers We ...
"Principal Component Analysis - the original paper" presentation @ Papers We ...
 

Similar to Useful date number and string sql queries

Oracle sql ppt2
Oracle sql ppt2Oracle sql ppt2
Oracle sql ppt2
Madhavendra Dutt
 
Intro to tsql unit 10
Intro to tsql   unit 10Intro to tsql   unit 10
Intro to tsql unit 10Syed Asrarali
 
Oracle sql functions
Oracle sql functionsOracle sql functions
Oracle sql functionsVivek Singh
 
SQL Functions and Operators
SQL Functions and OperatorsSQL Functions and Operators
SQL Functions and Operators
Mohan Kumar.R
 
SQL CHEAT SHEET
SQL CHEAT SHEETSQL CHEAT SHEET
SQL CHEAT SHEET
GadiOrellana
 
Sql functions
Sql functionsSql functions
Sql functions
G C Reddy Technologies
 
Python Statistics.pptx
Python Statistics.pptxPython Statistics.pptx
Python Statistics.pptx
MalathiNagarajan5
 
R Programming.pptx
R Programming.pptxR Programming.pptx
R Programming.pptx
kalai75
 
A few things about the Oracle optimizer - 2013
A few things about the Oracle optimizer - 2013A few things about the Oracle optimizer - 2013
A few things about the Oracle optimizer - 2013
Connor McDonald
 
Structured query language(sql)
Structured query language(sql)Structured query language(sql)
Structured query language(sql)
Huda Alameen
 
Data Management in R
Data Management in RData Management in R
Data Management in R
Sankhya_Analytics
 
Principal Components Analysis, Calculation and Visualization
Principal Components Analysis, Calculation and VisualizationPrincipal Components Analysis, Calculation and Visualization
Principal Components Analysis, Calculation and Visualization
Marjan Sterjev
 
Dax queries.pdf
Dax queries.pdfDax queries.pdf
Dax queries.pdf
ntrnbk
 
Hi,I have implemented increment() method. Please find the below up.pdf
Hi,I have implemented increment() method. Please find the below up.pdfHi,I have implemented increment() method. Please find the below up.pdf
Hi,I have implemented increment() method. Please find the below up.pdf
Ankitchhabra28
 
Sampling Data in T-SQL
Sampling Data in T-SQLSampling Data in T-SQL
Sampling Data in T-SQL
Tim Mills-Groninger
 
SQL coding at Sydney Measure Camp 2018
SQL coding at Sydney Measure Camp 2018SQL coding at Sydney Measure Camp 2018
SQL coding at Sydney Measure Camp 2018
Adilson Mendonca
 
Histograms: Pre-12c and now
Histograms: Pre-12c and nowHistograms: Pre-12c and now
Histograms: Pre-12c and now
Anju Garg
 

Similar to Useful date number and string sql queries (20)

Oracle sql ppt2
Oracle sql ppt2Oracle sql ppt2
Oracle sql ppt2
 
Intro to tsql unit 10
Intro to tsql   unit 10Intro to tsql   unit 10
Intro to tsql unit 10
 
Oracle sql functions
Oracle sql functionsOracle sql functions
Oracle sql functions
 
Les03 Single Row Function
Les03 Single Row FunctionLes03 Single Row Function
Les03 Single Row Function
 
SQL Functions and Operators
SQL Functions and OperatorsSQL Functions and Operators
SQL Functions and Operators
 
SQL CHEAT SHEET
SQL CHEAT SHEETSQL CHEAT SHEET
SQL CHEAT SHEET
 
Sql functions
Sql functionsSql functions
Sql functions
 
Python Statistics.pptx
Python Statistics.pptxPython Statistics.pptx
Python Statistics.pptx
 
R Programming.pptx
R Programming.pptxR Programming.pptx
R Programming.pptx
 
A few things about the Oracle optimizer - 2013
A few things about the Oracle optimizer - 2013A few things about the Oracle optimizer - 2013
A few things about the Oracle optimizer - 2013
 
Leip103
Leip103Leip103
Leip103
 
dbms.pdf
dbms.pdfdbms.pdf
dbms.pdf
 
Structured query language(sql)
Structured query language(sql)Structured query language(sql)
Structured query language(sql)
 
Data Management in R
Data Management in RData Management in R
Data Management in R
 
Principal Components Analysis, Calculation and Visualization
Principal Components Analysis, Calculation and VisualizationPrincipal Components Analysis, Calculation and Visualization
Principal Components Analysis, Calculation and Visualization
 
Dax queries.pdf
Dax queries.pdfDax queries.pdf
Dax queries.pdf
 
Hi,I have implemented increment() method. Please find the below up.pdf
Hi,I have implemented increment() method. Please find the below up.pdfHi,I have implemented increment() method. Please find the below up.pdf
Hi,I have implemented increment() method. Please find the below up.pdf
 
Sampling Data in T-SQL
Sampling Data in T-SQLSampling Data in T-SQL
Sampling Data in T-SQL
 
SQL coding at Sydney Measure Camp 2018
SQL coding at Sydney Measure Camp 2018SQL coding at Sydney Measure Camp 2018
SQL coding at Sydney Measure Camp 2018
 
Histograms: Pre-12c and now
Histograms: Pre-12c and nowHistograms: Pre-12c and now
Histograms: Pre-12c and now
 

More from Feras Ahmad

Oracle Fusion HCM Payroll Process Flow.pdf
Oracle Fusion HCM Payroll Process Flow.pdfOracle Fusion HCM Payroll Process Flow.pdf
Oracle Fusion HCM Payroll Process Flow.pdf
Feras Ahmad
 
Configure Flexfield Parameters in Value Sets for Document Records.docx
Configure Flexfield Parameters in Value Sets for Document Records.docxConfigure Flexfield Parameters in Value Sets for Document Records.docx
Configure Flexfield Parameters in Value Sets for Document Records.docx
Feras Ahmad
 
Building-Materials
Building-MaterialsBuilding-Materials
Building-Materials
Feras Ahmad
 
How to Debug the Fast Formula.pdf
How to Debug the Fast Formula.pdfHow to Debug the Fast Formula.pdf
How to Debug the Fast Formula.pdf
Feras Ahmad
 
Oracle Fusion Cloud Payroll Costing Query
Oracle Fusion Cloud Payroll Costing QueryOracle Fusion Cloud Payroll Costing Query
Oracle Fusion Cloud Payroll Costing Query
Feras Ahmad
 
Oracle Fusion Cloud sensitive data access audit
 Oracle Fusion Cloud sensitive data access audit Oracle Fusion Cloud sensitive data access audit
Oracle Fusion Cloud sensitive data access audit
Feras Ahmad
 
Oracle Cloud SQL FTE Positions Query
Oracle Cloud SQL FTE Positions QueryOracle Cloud SQL FTE Positions Query
Oracle Cloud SQL FTE Positions Query
Feras Ahmad
 
Legal Employer Details Query Oracle Fusion Cloud
Legal Employer Details Query Oracle Fusion CloudLegal Employer Details Query Oracle Fusion Cloud
Legal Employer Details Query Oracle Fusion Cloud
Feras Ahmad
 
Query Pre Payment details Oracle Fusion Cloud
Query Pre Payment details Oracle Fusion CloudQuery Pre Payment details Oracle Fusion Cloud
Query Pre Payment details Oracle Fusion Cloud
Feras Ahmad
 
The Goal with performance details Oracle Fusion Cloud
The Goal with performance details Oracle Fusion CloudThe Goal with performance details Oracle Fusion Cloud
The Goal with performance details Oracle Fusion Cloud
Feras Ahmad
 
All payroll elements with eligibility Oracle Fusion Cloud
All payroll elements with eligibility Oracle Fusion CloudAll payroll elements with eligibility Oracle Fusion Cloud
All payroll elements with eligibility Oracle Fusion Cloud
Feras Ahmad
 
Payroll costing details Oracle Fusion Cloud HCM
Payroll costing details Oracle Fusion Cloud HCMPayroll costing details Oracle Fusion Cloud HCM
Payroll costing details Oracle Fusion Cloud HCM
Feras Ahmad
 
Infolets and OTBI Deep link Actionable Reports - Configuration Work Book
Infolets and OTBI Deep link Actionable Reports - Configuration Work Book Infolets and OTBI Deep link Actionable Reports - Configuration Work Book
Infolets and OTBI Deep link Actionable Reports - Configuration Work Book
Feras Ahmad
 
DBI database Items Query Oracle Fusion Cloud
DBI database Items Query Oracle Fusion CloudDBI database Items Query Oracle Fusion Cloud
DBI database Items Query Oracle Fusion Cloud
Feras Ahmad
 
Query Worker Contracts Details Oracle Fusion Cloud
Query Worker Contracts Details Oracle Fusion CloudQuery Worker Contracts Details Oracle Fusion Cloud
Query Worker Contracts Details Oracle Fusion Cloud
Feras Ahmad
 
Query all roles and duties and privileges Oracle Fusion Cloud
Query all roles and duties and privileges Oracle Fusion CloudQuery all roles and duties and privileges Oracle Fusion Cloud
Query all roles and duties and privileges Oracle Fusion Cloud
Feras Ahmad
 
Oracle Fusion Cloud HCM Payroll Query
Oracle Fusion Cloud HCM Payroll QueryOracle Fusion Cloud HCM Payroll Query
Oracle Fusion Cloud HCM Payroll Query
Feras Ahmad
 
Oracle HCM Presentation 2020
Oracle HCM Presentation 2020Oracle HCM Presentation 2020
Oracle HCM Presentation 2020
Feras Ahmad
 
Oracle Fusion HCM vs E-Business Suite HRMS
Oracle Fusion HCM vs E-Business Suite HRMSOracle Fusion HCM vs E-Business Suite HRMS
Oracle Fusion HCM vs E-Business Suite HRMS
Feras Ahmad
 
2020 06-11 goverment KSA Summary VAT increase
2020 06-11 goverment KSA Summary VAT increase2020 06-11 goverment KSA Summary VAT increase
2020 06-11 goverment KSA Summary VAT increase
Feras Ahmad
 

More from Feras Ahmad (20)

Oracle Fusion HCM Payroll Process Flow.pdf
Oracle Fusion HCM Payroll Process Flow.pdfOracle Fusion HCM Payroll Process Flow.pdf
Oracle Fusion HCM Payroll Process Flow.pdf
 
Configure Flexfield Parameters in Value Sets for Document Records.docx
Configure Flexfield Parameters in Value Sets for Document Records.docxConfigure Flexfield Parameters in Value Sets for Document Records.docx
Configure Flexfield Parameters in Value Sets for Document Records.docx
 
Building-Materials
Building-MaterialsBuilding-Materials
Building-Materials
 
How to Debug the Fast Formula.pdf
How to Debug the Fast Formula.pdfHow to Debug the Fast Formula.pdf
How to Debug the Fast Formula.pdf
 
Oracle Fusion Cloud Payroll Costing Query
Oracle Fusion Cloud Payroll Costing QueryOracle Fusion Cloud Payroll Costing Query
Oracle Fusion Cloud Payroll Costing Query
 
Oracle Fusion Cloud sensitive data access audit
 Oracle Fusion Cloud sensitive data access audit Oracle Fusion Cloud sensitive data access audit
Oracle Fusion Cloud sensitive data access audit
 
Oracle Cloud SQL FTE Positions Query
Oracle Cloud SQL FTE Positions QueryOracle Cloud SQL FTE Positions Query
Oracle Cloud SQL FTE Positions Query
 
Legal Employer Details Query Oracle Fusion Cloud
Legal Employer Details Query Oracle Fusion CloudLegal Employer Details Query Oracle Fusion Cloud
Legal Employer Details Query Oracle Fusion Cloud
 
Query Pre Payment details Oracle Fusion Cloud
Query Pre Payment details Oracle Fusion CloudQuery Pre Payment details Oracle Fusion Cloud
Query Pre Payment details Oracle Fusion Cloud
 
The Goal with performance details Oracle Fusion Cloud
The Goal with performance details Oracle Fusion CloudThe Goal with performance details Oracle Fusion Cloud
The Goal with performance details Oracle Fusion Cloud
 
All payroll elements with eligibility Oracle Fusion Cloud
All payroll elements with eligibility Oracle Fusion CloudAll payroll elements with eligibility Oracle Fusion Cloud
All payroll elements with eligibility Oracle Fusion Cloud
 
Payroll costing details Oracle Fusion Cloud HCM
Payroll costing details Oracle Fusion Cloud HCMPayroll costing details Oracle Fusion Cloud HCM
Payroll costing details Oracle Fusion Cloud HCM
 
Infolets and OTBI Deep link Actionable Reports - Configuration Work Book
Infolets and OTBI Deep link Actionable Reports - Configuration Work Book Infolets and OTBI Deep link Actionable Reports - Configuration Work Book
Infolets and OTBI Deep link Actionable Reports - Configuration Work Book
 
DBI database Items Query Oracle Fusion Cloud
DBI database Items Query Oracle Fusion CloudDBI database Items Query Oracle Fusion Cloud
DBI database Items Query Oracle Fusion Cloud
 
Query Worker Contracts Details Oracle Fusion Cloud
Query Worker Contracts Details Oracle Fusion CloudQuery Worker Contracts Details Oracle Fusion Cloud
Query Worker Contracts Details Oracle Fusion Cloud
 
Query all roles and duties and privileges Oracle Fusion Cloud
Query all roles and duties and privileges Oracle Fusion CloudQuery all roles and duties and privileges Oracle Fusion Cloud
Query all roles and duties and privileges Oracle Fusion Cloud
 
Oracle Fusion Cloud HCM Payroll Query
Oracle Fusion Cloud HCM Payroll QueryOracle Fusion Cloud HCM Payroll Query
Oracle Fusion Cloud HCM Payroll Query
 
Oracle HCM Presentation 2020
Oracle HCM Presentation 2020Oracle HCM Presentation 2020
Oracle HCM Presentation 2020
 
Oracle Fusion HCM vs E-Business Suite HRMS
Oracle Fusion HCM vs E-Business Suite HRMSOracle Fusion HCM vs E-Business Suite HRMS
Oracle Fusion HCM vs E-Business Suite HRMS
 
2020 06-11 goverment KSA Summary VAT increase
2020 06-11 goverment KSA Summary VAT increase2020 06-11 goverment KSA Summary VAT increase
2020 06-11 goverment KSA Summary VAT increase
 

Recently uploaded

Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 

Recently uploaded (20)

Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 

Useful date number and string sql queries

  • 1. Useful Date, Number and String SQL Queries Geta sequence ofnumbers(1-12) in a table: We can generate sequence of numbersusingthe connectbyexpression..We canspecifythe upperlimit inthe level condition. SELECT ROWNUMMNTH FROMDUAL CONNECTBY LEVEL <= 12 GetWeekenddatesbetweentwoinput dates: selectdtdate,to_char(to_date(dt),'DY') day from(selecttrunc(to_date(:DATE_FROM)) +level - 1dt fromdual connectby trunc(to_date(:DATE_FROM))+level - 1 <= trunc(to_date(:DATE_TO))) where to_char(to_date(dt),'DY') in('SAT','SUN') Generate Random numberin SQL query: selecttrunc(DBMS_RANDOM.value(100,999)) fromdual SELECT ROUND(DBMS_RANDOM.VALUE() * 100) + 1 ASrandom_numFROMDUAL ConvertingComma Separated ValuesintoTable: The querycan come quite handywhenyouhave commaseparateddatastringthat youneedto convert intotable sothat you can use otherSQL querieslike IN orNOTIN. Here we are converting'AA,BB,CC,DD,EE,FF'stringtotable containingAA,BB,CCetc.as eachrow. Once you have thistable youcan joinitwithothertable to quicklydosome useful stuffs. WITH csv AS (SELECT 'AA,BB,CC,DD,EE,FF'AScsvdataFROMDUAL) SELECT REGEXP_SUBSTR (csv.csvdata,'[^,]+',1, LEVEL) pivot_char FROMDUAL, csv CONNECTBY REGEXP_SUBSTR (csv.csvdata,'[^,]+',1,LEVEL) IS NOT NULL WITH DATA AS( SELECT 'word1,word2, word3,word4, word5,word6' str FROM dual) SELECT TRIM(regexp_substr(str,'[^,]+',1, LEVEL)) str FROMDATA CONNECTBY instr(str,',',1, LEVEL - 1) > 0 ConvertingNumberinto Word: SELECT TO_CHAR(TO_DATE (1526, 'j'), 'jsp') FROMDUAL Getthe first day of the month: Quicklyreturnsthe firstdayof current month.Insteadof currentmonthyou wantto findfirstdayof monthwhere a date falls,replace SYSDATEwithany date column/value. SELECT TRUNC (SYSDATE,'MONTH') "Firstday of current month"FROMDUAL Getthe last day of the month: Thisqueryis similartoabove butreturnslastday of current month. One thingworthnotingisthat it automaticallytakescare of leapyear. So if youhave 29 daysinFeb,it will return29/2. If you wantto findthe last dayof a monthotherthan the current month,replace SYSDATEwithanydate
  • 2. column/value. SELECT TRUNC (LAST_DAY(SYSDATE)) "Lastday of current month"FROMDUAL Getthe first day of the Year: Firstday of year isalways1-Jan.This querycan be use instoredprocedure where youquicklywantfirst day of year forsome calculation. SELECT TRUNC (SYSDATE,'YEAR') "YearFirst Day"FROM DUAL Getthe last day of the year: SELECT ADD_MONTHS(TRUNC (SYSDATE,'YEAR'), 12) - 1 "Year Last Day" FROMDUAL Getnumber ofdays in current month: Thisqueryreturnsnumberof days incurrentmonth.You can change SYSDATEwithany date/value to knownumberof daysin that month. SELECT CAST(TO_CHAR(LAST_DAY (SYSDATE),'dd') ASINT) number_of_daysFROMDUAL Getnumber ofdays leftin current month: Belowquerycalculatesnumberof daysleftincurrentmonth SELECT SYSDATE,LAST_DAY (SYSDATE) "Last",LAST_DAY (SYSDATE) - SYSDATE "Days left"FROMDUAL Getnumber ofdays betweentwodates: Use thisqueryto getdifference betweentwodatesinnumberof days SELECT TRUNC(sysdate) - TRUNC(e.original_date_of_hire) FROMper_periods_of_service Display each monthsstart and enddate upto last month of the year: Thisquerydisplaysstartdate and enddate of eachmonthin currentyear.You mightwantto use thisfor certaintypesof calculations. SELECT ADD_MONTHS(TRUNC (SYSDATE,'MONTH'), i) start_date,TRUNC (LAST_DAY(ADD_MONTHS (SYSDATE,i))) end_date FROMXMLTABLE ('for$i in 0 toxs:int(D) return$i' PASSINGXMLELEMENT (d,FLOOR (MONTHS_BETWEEN (ADD_MONTHS(TRUNC (SYSDATE,'YEAR') - 1, 12),SYSDATE))) COLUMNS i INTEGER PATH '.') Getnumber ofseconds passedsince today (since 00:00 hr): SELECT (SYSDATE- TRUNC (SYSDATE)) *24 * 60 * 60 num_of_sec_since_morningFROMDUAL Getnumber ofseconds lefttoday (till 23:59:59 hr): SELECT (TRUNC(SYSDATE+1) - SYSDATE) * 24 * 60 * 60 num_of_sec_leftFROMDUAL GetMonth Namesin a year: selectto_char(add_months(sysdate,LEVEL),'MON') SEQUENCE, substr(to_char(add_months(sysdate,LEVEL),'DD-MON-YY','nls_date_language=english'),4,3) MONTH fromdual
  • 3. CONNECTBY LEVEL <= 12 orderby SEQUENCE ASC Hope thishelps.. Keepfollowingformore updates.