% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/get_resource_sql.R
\name{get_resource_sql}
\alias{get_resource_sql}
\title{Get PHS Open Data using SQL}
\usage{
get_resource_sql(sql)
}
\arguments{
\item{sql}{A single \code{SELECT} query (character).}
}
\value{
A \link[tibble:tibble-package]{tibble} with the query results. Only 32,000 rows
can be returned from a single SQL query.
}
\description{
Downloads data from the NHS Open Data platform using a SQL query. Similar to
\code{\link[=get_resource]{get_resource()}}, but allows more flexible server-side querying. This
function has a lower maximum row number (32,000 vs 99,999) for returned
results.
}
\details{
Only 32,000 rows can be returned from a single SQL query.
}
\section{SQL syntax}{

The resource ID must be double-quoted, e.g.
\verb{SELECT * FROM "58527343-a930-4058-bf9e-3c6e5cb04010"}, as must column names,
e.g. \code{"Year"}. Strings require single quotes, e.g. \code{'value'}. This syntax is
needed because the CKAN DataStore uses
\href{https://www.postgresql.org/docs/9.2/index.html}{PostgreSQL}.
}

\section{R raw strings}{

Enclosing the query in an R raw string avoids the need to escape embedded
quotes, e.g. \verb{\\"TotalCancelled\\"}. Square brackets are the recommended
delimiter, i.e. \code{r"[...]"}, because \verb{)"} within a query, e.g.
\code{SUM("TotalCancelled")}, would prematurely close the string. Another option
is \code{r"{...}"}, in the rare case that the query contains \verb{]"}.
}

\examples{
\dontshow{if (isTRUE(length(curl::nslookup("www.opendata.nhs.scot", error = FALSE)) > 0L)) withAutoprint(\{ # examplesIf}
# Basic query
cancelled_ops <- get_resource_sql(r"[
SELECT
    "TotalCancelled",
    "TotalOperations",
    "Hospital",
    "Month"
FROM
    "bcc860a4-49f4-4232-a76b-f559cf6eb885"
WHERE
    "Hospital" = 'D102H'
]")

# Joining two resources
hb_pop <- get_resource_sql(r"[
SELECT
    pops."Year",
    pops."HB",
    lookup."HBName",
    pops."AllAges"
FROM
    "27a72cc8-d6d8-430c-8b4f-3109a9ceadb1" AS pops
    JOIN "652ff726-e676-4a20-abda-435b98dd7bdc" AS lookup ON pops."HB" = lookup."HB"
WHERE
    pops."Sex" = 'All'
    AND pops."Year" > 2006
]")
\dontshow{\}) # examplesIf}
}
\seealso{
\code{\link[=get_resource]{get_resource()}} for downloading a resource without using a SQL query.
}
