- CFML Reference User Guide
- ColdFusion functions
- ColdFusion functions by category
- Functions a-b
- Abs
- ACos
- AddSOAPRequestHeader
- AddSOAPResponseHeader
- AjaxLink
- AjaxOnLoad
- ApplicationStop
- ArrayAppend
- ArrayAvg
- ArrayClear
- ArrayContains
- ArrayContainsNoCase
- ArrayDelete
- ArrayDeleteAt
- ArrayDeleteNoCase
- ArrayEach
- ArrayFilter
- ArrayFind
- ArrayFindAll
- ArrayFindAllNoCase
- ArrayFindNoCase
- ArrayInsertAt
- ArrayIsDefined
- ArrayIsEmpty
- ArrayLen
- ArrayMap
- ArrayMax
- ArrayMin
- ArrayNew
- ArrayPrepend
- ArrayReduce
- ArrayResize
- ArraySet
- ArraySetMetadata
- ArraySlice
- ArraySort
- ArraySum
- ArraySwap
- ArrayToList
- Asc
- ASin
- Atn
- AuthenticatedContext
- AuthenticatedUser
- BinaryDecode
- BinaryEncode
- BitAnd
- BitMaskClear
- BitMaskRead
- BitMaskSet
- BitNot
- BitOr
- BitSHLN
- BitSHRN
- BitXor
- BooleanFormat
- Abs
- Functions-c-d
- CacheGet
- CacheGetAllIds
- CacheGetMetadata
- CacheGetProperties
- CacheGetSession
- CacheIdExists
- CachePut
- CacheRegionExists
- CacheRegionNew
- CacheRegionRemove
- CacheRemove
- CacheRemoveAll
- CacheSetProperties
- CallStackDump
- CallStackGet
- CanDeSerialize
- Canonicalize
- CanSerialize
- Ceiling
- CharsetDecode
- CharsetEncode
- Chr
- CJustify
- Compare
- CompareNoCase
- Cos
- CreateDate
- CreateDateTime
- CreateObject
- CreateObject: .NET object
- CreateObject: COM object
- CreateObject: component object
- CreateObject: CORBA object
- CreateObject: Java or EJB object
- CreateObject: web service object
- CreateODBCDate
- CreateODBCDateTime
- CreateODBCTime
- CreateSignedJWT
- CreateEncryptedJWT
- CreateTime
- CreateTimeSpan
- CreateUUID
- CSRFGenerateToken
- CSRFVerifyToken
- DateAdd
- DateCompare
- DateConvert
- DateDiff
- DateFormat
- DatePart
- DateTimeFormat
- Day
- DayOfWeek
- DayOfWeekAsString
- DayOfYear
- DaysInMonth
- DaysInYear
- DE
- DecimalFormat
- DecodeForHTML
- DecodeFromURL
- DecrementValue
- Decrypt
- DecryptBinary
- DeleteClientVariable
- Deserialize
- DeserializeJSON
- DeserializeXML
- DirectoryCopy
- DirectoryCreate
- DirectoryDelete
- DirectoryExists
- DirectoryList
- DirectoryRename
- DollarFormat
- DotNetToCFType
- Duplicate
- Functions-e-g
- EncodeForCSS
- EncodeForDN
- EncodeForHTML
- EncodeForHTMLAttribute
- EncodeForJavaScript
- EncodeForLDAP
- EncodeForURL
- EncodeForXML
- EncodeForXMLAttribute
- EncodeForXpath
- Encrypt
- EncryptBinary
- EntityDelete
- EntityLoad
- EntityLoadByExample
- EntityLoadByPK
- EntityMerge
- EntityNew
- EntityReload
- EntitySave
- EntityToQuery
- Evaluate
- Exp
- ExpandPath
- FileClose
- FileCopy
- FileDelete
- FileExists
- FileGetMimeType
- FileIsEOF
- FileMove
- FileOpen
- FileRead
- FileReadBinary
- FileReadLine
- FileSeek
- FileSetAccessMode
- FileSetAttribute
- FileSetLastModified
- FileSkipBytes
- FileUpload
- FileUploadAll
- FileWrite
- FileWriteLine
- Find
- FindNoCase
- FindOneOf
- FirstDayOfMonth
- Fix
- Floor
- FormatBaseN
- GeneratePBKDFKey
- GenerateSecretKey
- GetApplicationMetadata
- GetAuthUser
- GetBaseTagData
- GetBaseTagList
- GetBaseTemplatePath
- GetClientVariablesList
- GetComponentMetaData
- GetContextRoot
- GetCPUUsage
- GetCurrentTemplatePath
- GetDirectoryFromPath
- GetEncoding
- GetException
- GetFileFromPath
- GetFileInfo
- GetFreeSpace
- GetFunctionCalledName
- GetFunctionList
- GetGatewayHelper
- GetHttpRequestData
- GetHttpTimeString
- GetK2ServerDocCount
- GetK2ServerDocCountLimit
- GetLocale
- GetLocaleDisplayName
- GetLocalHostIP
- GetMetaData
- GetMetricData
- GetPageContext
- GetPrinterInfo
- GetPrinterList
- GetProfileSections
- GetProfileString
- GetReadableImageFormats
- GetSafeHTML
- GetSAMLAuthRequest
- GetSAMLLogoutRequest
- GenerateSAMLSPMetadata
- GetSOAPRequest
- GetSOAPRequestHeader
- GetSOAPResponse
- GetSOAPResponseHeader
- GetSystemFreeMemory
- GetSystemTotalMemory
- GetTempDirectory
- GetTempFile
- GetTemplatePath
- GetTickCount
- GetTimeZoneInfo
- GetToken
- GetTotalSpace
- GetUserRoles
- GetVFSMetaData
- GetWriteableImageFormats
- Functions-h-im
- Hash
- HMac
- Hour
- HQLMethods
- HTMLCodeFormat
- HTMLEditFormat
- IIf
- ImageAddBorder
- ImageBlur
- ImageClearRect
- ImageCopy
- ImageCreateCaptcha
- ImageCrop
- ImageDrawArc
- ImageDrawBeveledRect
- ImageDrawCubicCurve
- ImageDrawLine
- ImageDrawLines
- ImageDrawOval
- ImageDrawPoint
- ImageDrawQuadraticCurve
- ImageDrawRect
- ImageDrawRoundRect
- ImageDrawText
- ImageFlip
- ImageGetBlob
- ImageGetBufferedImage
- ImageGetEXIFMetadata
- ImageGetEXIFTag
- ImageGetHeight
- ImageGetIPTCMetadata
- ImageGetIPTCTag
- ImageGetMetadata
- ImageGetWidth
- ImageGrayscale
- ImageInfo
- ImageMakeColorTransparent
- ImageMakeTranslucent
- ImageNegative
- ImageNew
- ImageOverlay
- ImagePaste
- ImageRead
- ImageReadBase64
- ImageResize
- ImageRotate
- ImageRotateDrawingAxis
- ImageScaleToFit
- ImageSetAntialiasing
- ImageSetBackgroundColor
- ImageSetDrawingColor
- ImageSetDrawingStroke
- ImageSetDrawingTransparency
- ImageSharpen
- ImageShear
- ImageShearDrawingAxis
- ImageTranslate
- ImageTranslateDrawingAxis
- ImageWrite
- ImageWriteBase64
- ImageXORDrawingMode
- Functions-in-k
- IncrementValue
- InputBaseN
- Insert
- Int
- InvalidateOauthAccesstoken
- Invoke
- InitSAMLAuthRequest
- InitSAMLLogoutRequest
- InvokeCFClientFunction
- IsArray
- IsAuthenticated
- IsAuthorized
- IsBinary
- IsBoolean
- IsClosure
- IsCustomFunction
- IsDate
- IsDateObject
- IsDDX
- IsDebugMode
- IsDefined
- IsImage
- IsImageFile
- IsInstanceOf
- IsIPv6
- IsJSON
- IsK2ServerABroker
- IsK2ServerDocCountExceeded
- IsK2ServerOnline
- IsLeapYear
- IsLocalHost
- IsNull
- IsNumeric
- IsNumericDate
- IsObject
- isOnline
- IsPDFArchive
- IsPDFFile
- IsPDFObject
- IsProtected
- IsQuery
- isSamlLogoutResponse
- isSafeHTML
- IsSimpleValue
- IsSOAPRequest
- IsSpreadsheetFile
- IsSpreadsheetObject
- IsStruct
- IsUserInAnyRole
- IsUserInRole
- IsUserLoggedIn
- IsValid
- IsValidOauthAccesstoken
- IsWDDX
- IsXML
- IsXmlAttribute
- IsXmlDoc
- IsXmlElem
- IsXmlNode
- IsXmlRoot
- JavaCast
- JSStringFormat
- Functions-l
- LCase
- Left
- Len
- ListAppend
- ListChangeDelims
- ListContains
- ListContainsNoCase
- ListDeleteAt
- ListEach
- ListFilter
- ListFind
- ListFindNoCase
- ListFirst
- ListGetAt
- ListInsertAt
- ListLast
- ListLen
- ListMap
- ListPrepend
- ListQualify
- ListReduce
- ListRemoveDuplicates
- ListRest
- ListSetAt
- ListSort
- ListToArray
- ListValueCount
- ListValueCountNoCase
- LJustify
- Location
- Log
- Log10
- LSCurrencyFormat
- LSDateFormat
- LSDateTimeFormat
- LSEuroCurrencyFormat
- LSIsCurrency
- LSIsDate
- LSIsNumeric
- LSNumberFormat
- LSParseCurrency
- LSParseDateTime
- LSParseEuroCurrency
- LSParseNumber
- LSTimeFormat
- LTrim
- Functions-m-r
- Max
- Mid
- Min
- Minute
- Month
- MonthAsString
- Now
- NumberFormat
- ObjectEquals
- ObjectLoad
- ObjectSave
- OnWSAuthenticate
- ORMClearSession
- ORMCloseAllSessions
- ORMCloseSession
- ORMEvictCollection
- ORMEvictEntity
- ORMEvictQueries
- ORMExecuteQuery
- ORMFlush
- ORMFlushall
- ORMGetSession
- ORMGetSessionFactory
- ORMIndex
- ORMIndexPurge
- ORMReload
- ORMSearch
- ORMSearchOffline
- ParagraphFormat
- ParameterExists
- ParseDateTime
- Pi
- PrecisionEvaluate
- ProcessSAMLResponse
- ProcessSAMLLogoutRequest
- Quarter
- PreserveSingleQuotes
- QueryAddColumn
- QueryAddRow
- QueryConvertForGrid
- QueryExecute
- QueryFilter
- QueryGetResult
- QueryGetRow
- QueryKeyExists
- QueryMap
- QueryNew
- QueryReduce
- QuerySetCell
- QuotedValueList
- QueryEach
- Rand
- Randomize
- RandRange
- ReEscape
- REFind
- REFindNoCase
- ReleaseComObject
- REMatch
- REMatchNoCase
- RemoveCachedQuery
- RemoveChars
- RepeatString
- Replace
- ReplaceList
- ReplaceNoCase
- REReplace
- REReplaceNoCase
- RestDeleteApplication
- RestSetResponse
- RestInitApplication
- Reverse
- Right
- RJustify
- Round
- RTrim
- Functions-s
- Second
- SendGatewayMessage
- SendSAMLLogoutResponse
- Serialize
- SerializeJSON
- SerializeXML
- SessionInvalidate
- SessionRotate
- SessionGetMetaData
- SessionInvalidate
- SessionRotate
- SetDay
- SetEncoding
- SetHour
- SetLocale
- SetMonth
- SetProfileString
- SetVariable
- SetYear
- Sgn
- Sin
- Sleep
- SpanExcluding
- SpanIncluding
- SpreadsheetAddAutoFilter
- SpreadsheetAddColumn
- SpreadsheetAddFreezePane
- SpreadsheetAddImage
- SpreadsheetAddInfo
- SpreadsheetAddPageBreaks
- SpreadsheetAddRow
- SpreadsheetAddRows
- SpreadsheetAddSplitPane
- SpreadsheetCreateSheet
- SpreadsheetDeleteColumn
- SpreadsheetDeleteColumns
- SpreadsheetDeleteRow
- SpreadsheetDeleteRows
- SpreadsheetFormatCell
- SpreadsheetFormatColumn
- SpreadsheetFormatCellRange
- SpreadsheetFormatColumn
- SpreadsheetFormatColumns
- SpreadsheetFormatRow
- SpreadsheetFormatRows
- SpreadsheetGetCellComment
- SpreadsheetGetCellFormula
- SpreadsheetGetCellValue
- SpreadsheetGetColumnCount
- SpreadsheetInfo
- SpreadsheetMergeCells
- SpreadsheetNew
- SpreadsheetRead
- SpreadsheetReadBinary
- SpreadsheetRemoveSheet
- SpreadsheetSetActiveSheet
- SpreadsheetSetActiveSheetNumber
- SpreadsheetSetCellComment
- SpreadsheetSetCellFormula
- SpreadsheetSetCellValue
- SpreadsheetSetColumnWidth
- SpreadsheetSetFooter
- SpreadsheetSetHeader
- SpreadsheetSetRowHeight
- SpreadsheetShiftColumns
- SpreadsheetShiftRows
- SpreadsheetWrite
- Sqr
- StripCR
- StructAppend
- StructClear
- StructCopy
- StructCount
- StructDelete
- StructEach
- StructFilter
- StructFind
- StructFindKey
- StructFindValue
- StructGet
- StructGetMetadata
- StructInsert
- StructIsEmpty
- StructKeyArray
- StructKeyExists
- StructKeyList
- StructMap
- StructNew
- StructReduce
- StructSetMetadata
- StructSort
- StructToSorted
- StructUpdate
- StoreSetMetadata
- StoreGetACL
- StoreGetMetadata
- StoreAddACL
- StoreSetACL
- Functions-t-z
- Tan
- ThreadJoin
- ThreadTerminate
- Throw
- TimeFormat
- ToBase64
- ToBinary
- ToScript
- ToString
- Trace
- Transactionandconcurrency
- TransactionCommit
- TransactionRollback
- TransactionSetSavePoint
- Trim
- UCase
- URLDecode
- URLEncodedFormat
- URLSessionFormat
- Val
- ValueList
- VerifyClient
- Week
- Wrap
- WriteDump
- WriteLog
- WriteOutput
- WSGetAllChannels
- WSGetSubscribers
- WSPublish
- WSSendMessage
- XmlChildPos
- XmlElemNew
- XmlFormat
- XmlGetNodeType
- XmlNew
- XmlParse
- XmlSearch
- XmlTransform
- XmlValidate
- Year
- YesNoFormat
- ColdFusion Tags
- ColdFusion tag summary
- ColdFusion tags by category
- Application framework tags
- Communications tags
- Database manipulation tags
- Data output tags
- Debugging tags
- Exception handling tags
- Extensibility tags
- File management tags
- Flow-control tags
- Forms tags
- Internet Protocol tags
- Page processing tags
- Security tags
- Variable manipulation tags
- Other tags
- Tags a-b
- Tags c
- Tags f
- cffeed
- cffile
- cffile action = "append"
- cffile action = "copy"
- cffile action = "delete"
- cffile action = "move"
- cffile action = "read"
- cffile action = "readBinary"
- cffile action = "rename"
- cffile action = "upload"
- cffile action = "uploadAll"
- cffile action = "write"
- cffileupload
- cffinally
- cfflush
- cfform
- cfformgroup
- cfformitem
- cfftp
- cfftp: Connection: file and directory operations
- cfftp: Opening and closing FTP server connections
- cfftp : Opening and closing secure FTP server connections
- cfftp action = "listDir"
- cffunction
- Tags g-h
- Tags i
- Tags j-l
- cfjava
- cflayout
- cflayoutarea
- cfldap
- cflocation
- cflock
- cflog
- cflogin
- cfloginuser
- cflogout
- cfloop
- cfloop : conditional loop
- cfloop : index loop
- cfloop : looping over a COM collection or structure
- cfloop : looping over a date or time range
- cfloop : looping over a list, a file, or an array
- cfloop : looping over a query
- Tags m-o
- cfmail
- cfmailparam
- cfmailpart
- cfmap
- cfmapitem
- cfmediaplayer
- cfmenu
- cfmenuitem
- cfmessagebox
- cfmodule
- cfNTauthenticate
- cfoauth
- cfobject
- cfobject: .NET object
- cfobject: COM object
- cfobject: component object
- cfobject: CORBA object
- cfobject: Java or EJB object
- cfobject: web service object
- cfobjectcache
- cfoutput
- Tags p-q
- Tags r-s
- Tags t
- Tags u-z
- CFML Reference
- Reserved words and variables
- Ajax JavaScript functions
- Ajax JavaScript functions
- Function summary Ajax
- ColdFusion.Ajax.submitForm
- ColdFusion.Autosuggest.getAutosuggestObject
- ColdFusion.Layout.enableSourceBind
- ColdFusion.MessageBox.getMessageBoxObject
- ColdFusion.ProgressBar.getProgressBarObject
- ColdFusion.MessageBox.isMessageBoxDefined
- JavaScriptFunctionsinColdFusion9Update1
- ColdFusion ActionScript functions
- ColdFusion mobile functions
- Application.cfc reference
- Script functions implemented as CFCs
- ColdFusion Flash Form style reference
- Styles valid for all controls
- Styles for cfform
- Styles for cfformgroup with horizontal or vertical type attributes
- Styles for box-style cfformgroup elements
- Styles for cfformgroup with accordion type attribute
- Styles for cfformgroup with tabnavigator type attribute
- Styles for cfformitem with hrule or vrule type attributes
- Styles for cfinput with radio, checkbox, button, image, or submit type attributes
- Styles for cftextarea tag and cfinput with text, password, or hidden type attributes
- Styles for cfselect with size attribute value of 1
- Styles for cfselect with size attribute value greater than 1
- Styles for cfcalendar tag and cfinput with dateField type attribute
- Styles for the cfgrid tag
- Styles for the cftree tag
- ColdFusion Flash Form Style Reference
- ColdFusion event gateway reference
- ColdFusion Event Gateway reference
- addEvent
- CFEvent
- CFEventclass
- Constructor
- Gateway development interfaces and classes
- getStatus
- setCFCPath
- setCFCMethod
- getOriginatorID
- getLogger
- getBuddyList
- getBuddyInfo
- IM gateway message sending commands
- IM Gateway GatewayHelper class methods
- onIncomingMessage
- onIMServerMessage
- onBuddyStatus
- onAddBuddyResponse
- onAddBuddyRequest
- IM Gateway CFC incoming message methods
- IM gateway methods and commands
- CFML CFEvent structure
- warn
- info
- setOriginatorID
- data command
- submit Multi command
- submit command
- setGatewayType
- setGatewayID
- setData
- setCFCListeners
- outgoingMessage
- getStatusTimeStamp
- numberOfMessagesReceived
- numberOfMessagesSent
- removeBuddy
- removeDeny
- removePermit
- setNickName
- setPermitMode
- setStatus
- SMS Gateway CFEvent structure and commands
- SMS Gateway incoming message CFEvent structure
- getStatusAsString
- getProtocolName
- getPermitMode
- getPermitList
- getNickName
- getName
- getDenyList
- getCustomAwayMessage
- getQueueSize
- getMaxQueueSize
- getHelper
- getGatewayType
- getGatewayServices
- getGatewayID_1
- getGatewayID
- getData
- getCFCTimeout
- setCFCTimeout
- getCFCPath
- getCFCMethod
- GatewayServices class
- Gateway interface
- GatewayHelper interface
- addPermit
- addDeny
- addBuddy
- error
- debug
- Logger class
- stop
- start
- CFML event gateway SendGatewayMessage data parameter
- restart
- fatal
- SMS gateway message sending commands
- ColdFusion C++ CFX Reference
- ColdFusion Java CFX reference
- WDDX JavaScript Objects
- Cloud services
- ColdFusion and GCP Storage
- ColdFusion and GCP Firestore
- ColdFusion and GCP PubSub
- ColdFusion and Amazon S3
- ColdFusion and DynamoDB
- ColdFusion and Amazon SQS
- ColdFusion and Amazon SNS
- ColdFusion and MongoDB
- ColdFusion and Azure Blob
- ColdFusion and Azure Service Bus
- Multi-cloud storage services
- Multi-cloud RDS databases
- ColdFusion and Azure Cosmos DB
This tag is unsupported in CFFiddle.
Description
Passes queries or SQL statements to a data source.Adobe recommends that you use the cfqueryparam tag within every cfquery tag, to help secure your databases from unauthorized users.
Category
Syntax
<cfquery name = "query name" blockFactor = "block size" cachedAfter = "date" cacheID = "ID" cacheRegion = "region" cachedWithin = "timespan" disableAutoGenKeys="true|false" dataSource = "data source name" dbtype = "query" debug = "yes|no" fetchClientInfo = "yes|no" maxRows = "number" ormoptions = #orm options structure# password = "password" result = "result name" timeout = "seconds" username = "user name" returnType="array | json/array | query | struct | json/struct"> </cfquery>
You can specify this tag's attributes in an attributeCollection attribute whose value is a structure. Specify the structure name in the attributeCollection attribute and use the tag's attribute names as structure keys
See also
cfdbinfo, cfinsert, cfprocparam, cfprocresult, cfqueryparam, cfstoredproc, cftransaction, cfupdate; Optimizing database use in Optimizing ColdFusion applications in the Developing ColdFusion Applications
History
ColdFusion (2021 release): Added the attribute returnType.
ColdFusion (2018 release): Added the parameter disableAutoGenKeys.
ColdFusion 11: Removed the following attributes:
- connectString
- dbName
- dbServer
- provider
- providerDSN
- sql
In addition, the following dbType attribute values have been removed:
- dynamic
- ODBC
- Oracle73
- Oracle80
- Sybase11
- OLEDB
- DB2
ColdFusion 10: Added the following attributes: fetchClientInfo, cacheID, cacheRegion, clientInfo}}
ColdFusion 9.0.1: Introduced support for HQL queries; added the attribute {{ormoptions.
ColdFusion 9: Datasource attribute is optional now.
ColdFusion 8: Added the result variable that specifies the ID of a row.
ColdFusion MX 7:
- Added the result attribute for specifying an alternate name for the structure that holds the result variables.
- Added result variables for the SQL statement executed ( sql ), the number of records returned ( recordcount ), whether the query was cached (cached), an array of cfqueryparam values ( sqlparameters ), and the list of columns in the returned query ( columnlist ).
ColdFusion MX: - Changed Query of Queries behavior: it now supports a larger subset of standard SQL.
- Changed dot notation support: ColdFusion now supports dot notation within a record set name. ColdFusion interprets such a name as a structure.
- Deprecated the connectString, dbName, dbServer, provider, providerDSN , and sql attributes, and all values of the dbtype attribute except query. They do not work, and might cause an error, in releases later than ColdFusion 5.
- New query object variable: cfquery.ExecutionTime.
- No longer supports native drivers. It now uses JDBC (and ODBC-JDBC bridge) for database connectivity.
Attributes
Attribute |
Req/Opt |
Default |
Description |
---|---|---|---|
name |
Required |
|
Name of query. Used in page to reference query record set. Must begin with a letter. Can include letters, numbers, and underscores. |
blockFactor |
Optional |
1 |
Maximum rows to get at a time from server. Range: 1 - 100. Might not be supported by some database systems. |
cachedAfter |
Optional |
|
Date value (for example, April 16, 1999, 4-16-99). If date of original query is after this date, ColdFusion uses cached query data. To use cached data, current query must use same SQL statement, data source, query name, user name, password. A date/time object is in the range 100 AD-9999 AD. |
cacheID |
Optional |
|
ID to be used to store query result in cache. This ID can be used to either retrieve or remove query from cache |
cacheRegion |
Optional |
|
Cache region to be used to cache query result. If not specified, by default query is cached in the QUERY region. |
cachedWithin |
Optional |
|
Timespan, using the CreateTimeSpan function. If original query date falls within the time span, cached query data is used. CreateTimeSpan defines a period from the present, back. Takes effect only if query caching is enabled in the Administrator. To use cached data, the current query must use the same SQL statement, data source, query name, user name, and password. |
clientInfo |
Optional |
|
Structure containing properties of the client to be set on the database connection. |
dataSource |
Optional |
|
The Datasource attribute is now optional. If omitted, the query uses the datasourcespecified in the application. If it is not specified in either places, then the error will be thrown. |
dbtype |
Optional |
|
Results of a query as input. Specify either dbtype or dataSource.ColdFusion supports HQL in cfquery. Therefore, you can specify dbtype="hql" as shown in the following example:<cfquery dbtype="hql" name="artists" ormoptions=#{cachename=""}#>from Artists where firstname=<cfqueryparam value="Aiden"></cfquery> |
debug |
Optional; value and equals sign may be omitted |
|
· yes, or if omitted: if debugging is enabled, but the Administrator Database Activity option is not enabled, displays SQL submitted to the data source and number of records returned by query. · no: if the Administrator Database Activity option is enabled, suppresses display. |
disableAutoGenKeys | Optional | false | Specify true to disable retrieval of autogenerated keys. In previous versions of ColdFusion, you could set this attribute at the datasource lavel. In the 2018 release of ColdFusion, you can set it at the query level. |
fetchClientInfo |
Optional |
no |
If set yes, returns a struct with the key-value pair passed by the last query. |
maxRows |
Optional |
-1 (All) |
Maximum number of rows to return in record set. |
ormoptions |
Optional |
|
A struct that takes orm options for executing HQL. Applies only if dbtype is set to hql. |
password |
Optional |
|
Overrides the password in the data source setup. |
result |
Optional |
|
Name for the structure in which cfquery returns the result variables. For more information, see Usage. |
timeout |
|
|
Maximum number of seconds that each action of a query is permitted to execute before returning an error. The cumulative time may exceed this value. |
username |
Optional |
|
Overrides user name in the data source setup. |
returnType | Optional | Values are:
|
Usage
Use this tag to execute a SQL statement against a ColdFusion data source. Although you can use the cfquery tag to execute any SQL Data Definition Language (DDL) or Data Manipulation Language (DML) statement, you typically use it to execute a SQL SELECT statement.
To call a stored procedure, use the cfstoredproc tag.
This tag creates a query object, providing this information in query variables:
Variable name |
Description |
---|---|
query_name.currentRow |
Current row of query that cfoutput is processing. |
query_name.columnList |
Comma-separated list of the query columns. |
query_name.RecordCount |
Number of records (rows) returned from the query.
|
The cfquery tag also returns the following result variables in a structure. You can access these variables with a prefix of the name you specified in the result attribute. For example, if you assign the name myResult to the result attribute, you would retrieve the name of the SQL statement that was executed by accessing #myResult.sql#. The result attribute provides a way for functions or CFCs that are called from multiple pages, possibly at the same time, to avoid overwriting results of one call with another. The result variable of INSERT queries contains a key-value pair that is the automatically generated ID of the inserted row; this is available only for databases that support this feature. If more than one record was inserted, the value can be a list of IDs. The key name is database-specific.
Variable name |
Description |
---|---|
result_name.sql |
The SQL statement that was executed. |
result_name.recordcount |
Number of records (rows) returned from the query. |
result_name.cached |
True if the query was cached; False otherwise. |
result_name.sqlparameters |
An ordered Array of cfqueryparam values. |
result_name.columnList |
Comma-separated list of the query columns. |
result_name.ExecutionTime |
Cumulative time required to process the query. |
result_name.IDENTITYCOL |
SQL Server only. The ID of an inserted row. |
result_name.ROWID |
Oracle only. The ID of an inserted row. This is not the primary key of the row, although you can retrieve rows based on this ID. |
result_name.SYB_IDENTITY |
Sybase only. The ID of an inserted row. |
result_name.SERIAL_COL |
Informix only. The ID of an inserted row. |
result_name.GENERATED_KEY | MySQL only. The ID of an inserted row. MySQL 3 does not support this feature. |
result_name.GENERATEDKEY | Supports all databases. The ID of an inserted row. |
You can cache query results and execute stored procedures. For information about this and about displaying cfquery output, see the Developing ColdFusion Applications. Because the timeout attribute only affects the maximum time for each suboperation of a query, the cumulative time may exceed its value. To set a timeout for a page that might get a very large result set, set the Administrator > Server Settings > Timeout Requests option to an appropriate value or use the RequestTimeout attribute of the cfsetting tag (for example, <cfsetting requestTimeout="300">).
The Caching page of the ColdFusion Administrator specifies the maximum number of cached queries. Setting this value to 0 disables query caching.
You cannot use ColdFusion reserved words as query names. You cannot use SQL reserved words as variable or column names in a Query of Queries, unless they are escaped. The escape character is the bracket []; for example:
SELECT [count] FROM MYTABLE.
For a list of reserved keywords in ColdFusion, see Escaping reserved keywords in Query of Queries user guide in the Developing ColdFusion Applications.
Example 1: Getting started
<!--- Get employee names from database ---> <cfquery name="getEmployees" datasource="cfdocexamples"> SELECT FIRSTNAME,LASTNAME FROM EMPLOYEES </cfquery> <!--- Create HTML page ---> <HTML> <head> <title> List of Employees </title> </head> <body> <h1> Employee List </h1> <!--- List out employees---> <cfoutput query="getEmployees"> #FIRSTNAME# #LASTNAME# <br/> </cfoutput> </body> </HTML>
Example 2: Using tables
<!--- Get employee names from database ---> <cfquery name="getEmployees" datasource="cfdocexamples"> SELECT FIRSTNAME,LASTNAME,EMAIL,PHONE FROM EMPLOYEES </cfquery> <!--- Create HTML page ---> <html> <head> <title> Table of Employees </title> </head> <body> <table border="1"> <!--- Loop through the database ---> <cfoutput query="getEmployees"> <tr> <td> #FIRSTNAME# #LASTNAME# </td> <td> #EMAIL# </td> <td> #PHONE# </td> </tr> </cfoutput> </table> </body> </html>
Example 3: Using the result attribute
<!--- Get employee names from database ---> <cfquery name="getEmployees" datasource="cfdocexamples" result="result"> SELECT FIRSTNAME,LASTNAME,EMAIL,PHONE FROM EMPLOYEES </cfquery> <cfdump var="#result#" > <cfoutput> <!--- Display count of records ---> #result.RecordCount# </cfoutput>
Output
Example 4: Using the password attribute
Many database configurations require authentication (in the form of a username and password) before you can query the database. You can add authentication using the username and password attributes.
Note that You can also configure the user name and password in the datasource in the ColdFusion Administrator. Specifying the authentication details in your query overrides the username and password in the ColdFusion Administrator.
<cfquery datasource="cfdocexamples" username="myusername" password="mypassword"> select * from Employees </cfquery>
Example 5: Limiting the number of records
You can limit the number of rows to be returned by using the maxrows attribute.
<cfquery name="getEmployees" datasource="cfdocexamples" result="result" maxrows="10"> SELECT FIRSTNAME,LASTNAME,EMAIL,PHONE FROM EMPLOYEES </cfquery> <cfdump var="#result#" > <cfoutput> <!--- Display count of records ---> #result.RecordCount# </cfoutput>
Example 6: Using the timeout attribute
You can set a timeout limit using the timeout attribute. A timeout is useful in preventing requests that are running for more than the limit set.
The timeout attribute sets the maximum number of seconds that each action of a query is allowed to execute before returning an error.
<cfquery name="getEmployees" datasource="cfdocexamples" timeout="20" > SELECT FIRSTNAME,LASTNAME,EMAIL,PHONE FROM EMPLOYEES </cfquery> <cfdump var="#getEmployees#" >
Example 7: Cached queries
The volume of traffic to your web site or applications impacts the performance of your site or application. To enhance the performance, you can cache your database queries.
A cached query is a query that has its results stored in the server's memory. The results are stored when the query is first run. Whenever you run the query thereafter, ColdFusion retrieves the results from memory.
You can cache a query using the cachedAfter attribute.
<cfquery name="getEmployees" datasource="cfdocexamples" cachedafter="10-15-2018" > SELECT FIRSTNAME,LASTNAME,EMAIL,PHONE FROM EMPLOYEES </cfquery> <cfdump var="#getEmployees#" >
You can also cache a query using the cachedWithin attribute with the CreateTimeSpan function.
In the example below, if the query's cached data is older than 60 seconds, the query is re-run. Otherwise, the cached data is used.
<cfquery name="getEmployees" datasource="cfdocexamples" cachedwithin="#CreateTimespan(0,0,60,0)#" > SELECT FIRSTNAME,LASTNAME,EMAIL,PHONE FROM EMPLOYEES </cfquery> <cfdump var="#getEmployees#" >
Example 8- Return type is array
<cfquery name="getEmployees" datasource="cfArtGallery" result="myquery" RETURNTYPE = "array"> select ARTID,ARTISTID,ARTNAME from art where ARTID < 2 </cfquery> <cfoutput>#getEmployees[1].ARTID# #getEmployees[1].ARTISTID# #getEmployees[1].ARTNAME#</cfoutput>
Example 9- Return type is json/array
<cfquery name="getEmployees" datasource="cfArtGallery" result="myquery" RETURNTYPE = "json/array"> select ARTID,ARTISTID,ARTNAME from art where ARTID < 2 </cfquery> <cfset record=deserializeJSON(getEmployees)> <cfoutput>#record[1].ARTID# #record[1].ARTISTID# #record[1].ARTNAME# #getEmployees#</cfoutput>
Example 10- Return type is default query
<cfquery name="getEmployees" datasource="cfArtGallery" result="myquery"> select ARTID,ARTISTID,ARTNAME from art where ARTID < 2 </cfquery> <cfset record=QueryGetRow(getEmployees,1)> <cfoutput>#record.ARTID# #record.ARTISTID# #record.ARTNAME#</cfoutput>