Questions tagged [select]

A core SQL statement, SELECT retrieves data from one or more tables or other sources of row set data such as views or table-valued functions.

SELECT is a core SQL statement that retrieves data from various sources, typically tables, views or functions that return record set data.

Select statements can join data from multiple sources including the output of other embedded select statements (known as sub-queries). Joining is one of the key defining characteristics of a relational database management system.

a basic SELECT statement is of the form:

SELECT [column list]
  FROM [sources]
 WHERE [conditions]

A more complex query can be composed of a variety of primitive operations, including:

Joins take two data sets (tables, subquery results or other sources) and link them together based on some logical function such as equality of the columns. Some join predicates can use indexes and allow optimisations in the query that may not be possible with others. In some cases it may be necessary to re-structure the query so it can (for example) make use of an index, even though the original query was semantically equivalent to the modified version. A basic join query has the form:

SELECT [column list]
  FROM [table 1]
  JOIN [table 2]
    ON [some predicate such as equality of two columns]

A join may be optional on one or both sides, called an outer join. If data on the optional side of the join is not present, then NULLs will be returned in the place of columnar data from the data set on that side of the join.

Nested Subqueries are SQL statements embedded within a query that can be used by outer queries by selecting from that data set or joining against another. A query that joins something against the output of a nested subquery looks something like:

SELECT a.[columns]
      ,b.[columns]
  FROM [table1] a
  JOIN (SELECT [columns]
          FROM [ . . . ]) b
    ON [join condition]

Correlated Subqueries are sub-queries that use some data from the parent query. A correlated subquery might look something like:

SELECT a.[columns]
  FROM [table1] a
 WHERE EXISTS
       (SELECT 1
          FROM [table2] b
         WHERE [some condition involving data from both a and b])

In this case, note that the condition involves data from both a and b. The defining feature of a correlated subquery is that it needs data from the parent to resolve the predicate.

WHERE Clause This allows arbitrary logical conditions to be applied. In some cases these can be applied in joins as well, and it may be preferable to explicitly apply them in the join condition so the query optimiser can use them properly.

Common Table Expressions (CTEs) are an abstraction mechanism that can be used to re-use common logic in a query, or for certain facilities such as recursion. A CTE may also take parameters, and has a form similar to:

WITH [name of cte] (parameters) AS
     (SELECT [columns]
        FROM [sources]
       WHERE [predicates])  -- This could be arbitrarily complex
SELECT [. . .]

Aggreates and filters A query can aggregate data within groupings using the GROUP BY clause, and can filter after the aggregate using HAVING.

Various other features may be present in certain dialects, for example windowing functinons, Oracle's CONNECT BY, applying table valued functions (CROSS APPLY) or using table valued functions as data sources.

1075 questions
6
votes
4 answers

Return int value from boolean field in SQL select

Is there a way to return an int value for a boolean field in a sql select statement?
David Gauer
  • 61
  • 1
  • 1
  • 2
4
votes
1 answer

Select columns from 4 tables

First thing, I am totally new to SQL. I saw some tutorials, videos, tried searching but didn't find what I needed. I know it has asked before, but I couldn't find it. What I need to find is basically like: Select Company.Name, Programmer.Name,…
ArbenM
  • 69
  • 1
  • 3
3
votes
3 answers

Select over 2 select queries

I have two tables: work: id w_date other stuff 1 2017-05-10 1 2017-05-08 3 2017-05-17 home: id h_date other stuff 1 2017-05-01 4 2017-05-06 1 2017-05-14 Now I need a query that I get all dates where id is 1.…
fips123
  • 133
  • 3
2
votes
2 answers

"For each group of results fullfilling condition X, select only result with smallest column value A"

I have a table with data and dates like so: DECLARE @p TABLE (P_key int, P_Data char(1), P_ValidUntil datetime) INSERT @p VALUES (20, 'T', '2003-02-28') INSERT @p VALUES (21, 'U', '2005-05-31') INSERT @p VALUES (30, 'V', '2006-09-30') INSERT @p…
B3ret
  • 145
  • 3
2
votes
5 answers

How define select, if bridge pair may have 3 players?

Normaly a pair has 2 players, but if there is an odd number of players at the club, one 'pair' has 3 players. Table, members: pair, player_id 1 1 1 2 2 3 2 4 3 5 3 6 4 7 4 8 5 9 5 10 6 11 6 12 6 13 table players: id name 1 Smith 2 Brown 3…
otm
  • 47
  • 6
2
votes
5 answers

Exclude composite key from select

I have 2 identical DBs, one of the tables has C1, C2, C3 , composite key. I'm trying to get the rows from B that are not present in DB A. I have tried many approaches, but at this time I even can't re-use this suggestion due too the late hour. I…
Ezeq
  • 107
  • 1
  • 2
  • 8
1
vote
1 answer

4 tables, find department with the highest average salary

ABC is an organization operating in a certain country. Below are the data for the database that manages the information on this organization's employees: employee(employee_name, street, city) works(employee_name, department_name, position,…
ArbenM
  • 69
  • 1
  • 3
1
vote
0 answers

Grafana - combine multiple SELECT from different measurments

I'm totally new here, I tried to find solution and I found this: Influxdb and Grafana combine multiple SELECT but this works fine if we have different fields from the same measurement, but this does not work (for me) when adding values from…
Mike
  • 11
  • 1
  • 3
0
votes
1 answer

Query to select distinct name based on several factors

I have a table with the following data (simplified here): ID | PolicyName | Setting | State | Value 1 Default DiskUsage Enabled 1 2 Default Memory Enabled 1 3 Default CPU Enabled 0 4 Personal DiskUsage Enabled 0 5 Personal Memory Enabled 1 6…
0
votes
1 answer

Using count() and sum() in a calculation in a select

I am trying to do the following in a single select. We have a SAAS that has Company records and User records. A User is a member of a Company (Company.CompanyId = User.CompanyId). In the User record we track bandwidth usage for that user (for the…
David Thielen
  • 179
  • 1
  • 9
0
votes
1 answer

Replace course_id with course_name in results

I have schedules of class times and I place the course id in the classtimes. When I run the query I see that in 30 minute times what courses are scheduled, but in the results I want to see the name not the id. SELECT TOP (2000)…
Rinkratt
  • 1
  • 1
0
votes
1 answer

Select for result both of two column values

Hoping for syntax to select for result that has both of 2 possible column values. Right now I'm doing select distinct f1,f2,f3 from table where f3 in ('val1','val2') and outputting the text file and then looking for the cases where both val1 and…
0
votes
0 answers

Average amount of orders per hour in the last X days per merchant

I have the following table named Orders: MerchantID (INT) OrderID (VARCHAR2) OrderAmount (INT) CreatedDate (DATE/TIME) I need to create a query that returns the average amount of orders per hour in the last X days per merchant. Trying…
0
votes
1 answer

Selecting attributes from multiple tables via foreign key

Apologies if this question has already been answered. Couldn't find the answer myself. I'm trying to work out the SQL to extract data from one table which is being referenced from another table. My explanation might be terrible due to looking at it…
Shaun
  • 9
  • 3
0
votes
1 answer

Finding Conflicting Combinations Using SQL

Say I have table called "Everyone_Loves_Relationships" which contains three fields: Boy_Name, Girl_Name, Relationship_Status. The list goes like this: Boy_Name Girl_Name Relationship_Status Tony Carol No Simon Julia …
Faust
  • 103
  • 2
1
2