Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm trying to figure out what type of `SELECT` I need to write in order to pull a string that starts after a particular character and ends after another character. My data appears as follows:
```
Path
------------------------------------------------------
\1231254-0000001000-14671899.PDF
\74-0000001001-14672073.PDF
\6... | You could use `PARSENAME(REPLACE())` to do this:
```
SELECT PARSENAME(REPLACE(path, '-', '.'), 2) FROM tableName
```
`PARSENAME()` takes a string and splits it by the period characters `.` and returns the token located at the second parameter's position. | You could use `substring` and `charindex` if the format of the column is consistent.
[Fiddle](http://www.sqlfiddle.com/#!6/1e5568/2)
```
select reverse (
substring (
reverse(path),
charindex('.',reverse(path))+1,
charindex('-', reverse(path))- charindex('.',... | Pull text following and preceded by two differing delimiters of a variable length string? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have two tables:
```
create table FOO (
id integer primary key
);
create table BAR (
id primary key,
fooId integer -- yeah, this *should* be a foreign key
);
insert into FOO values (10);
insert into FOO values (11); -- no BAR
insert into BAR values (20, 10); -- OK
insert into BAR values (21, 3); -- No FO... | Do a `UNION ALL` with two `NOT IN`'s:
```
select id, null from FOO where id not in (select fooId from bar where fooId is not null)
union all
select null, id from BAR where fooId not in (select id from foo where id is not null)
```
Or, a `FULL OUTER JOIN`:
```
select distinct f.id, b.id
from foo f
full outer join b... | Just use `not exists` (or `not in` or `left join` with a `where` clause):
```
select b.*
from bar b
where not exists (select 1 from foo f where f.id = b.fooid);
```
The only *broken* relationships are those where `bar.fooid` does not match a valid `foo.id`. Having a value in `foo` with no corresponding value in `bar`... | List problems in foreign key relations | [
"",
"sql",
"foreign-key-relationship",
""
] |
*I have looked at related Qs on Stack*.
I am trying to sort my query to display month in ascending order. A similar post on Stack said that I must indicate "ASC", but this doesn't work for me. I have written an Order By. I cannot figure out why it is not working.
```
SELECT DATENAME( MONTH,(Submission.SubmissionDate)... | A simple option is to add `MONTH(Submission.SubmissionDate)` to your `group by` clause, and `order by` that as well:
```
SELECT DATENAME( MONTH,(Submission.SubmissionDate)) AS [Date]
FROM Submission
GROUP BY MONTH(Submission.SubmissionDate), DATENAME( MONTH,(Submission.SubmissionDate))
ORDER BY MONTH(Submiss... | ```
SELECT DATENAME( MONTH, Submission.SubmissionDate) AS [Date]
FROM Submission
ORDER BY datepart(mm,Submission.SubmissionDate)
```
You don't need a `group by` (for the query shown). Also, when you `order by` `month name` it would return results in the alphabetical order of `month name`. You should not use ... | sorting month in ascending order | [
"",
"sql",
"sql-server",
""
] |
I have a table with records and a period of time for each record, like reservations for instance. So my records look like this:
```
Table-reservations
id room datefrom dateto
1 'one' '2015-09-07' '2015-09-12'
2 'two' '2015-08-11' '2015-09-02'
3 'three' '2015-06-11' '2015-06-14'
4 'two' ... | You'll want to check that records don't exist where 'date from' is less than or equal to the end date in your range and 'date to' is greater than or equal to the start date in your range.
```
select t1.room
from reservations t1
where not exists (
select *
from reservations t2
where t2.room = t1.room
and t2.dat... | This might be easier to understand.
Assuming you have another table for rooms.
```
SELECT *
FROM rooms
WHERE NOT EXISTS (SELECT id
FROM reservations
WHERE reservations.room = rooms.id
AND datefrom >= '2015-08-13'
AND dateto <= '2015-08-... | Select * from table where desired period does not overlap with existing periods | [
"",
"mysql",
"sql",
""
] |
I have a row in a databasetable that is on the following form:
```
ID | Amount | From | To
5 | 5439 | 01.01.2014 | 05.01.2014
```
I want to split this up to one row pr month using SQL/T-SQL:
```
Amount | From
5439 | 01.01.2014
5439 | 02.01.2014
5439 | 03.01.2014
5439 | 04.01.2014
543... | You can use a [tally table](http://www.sqlservercentral.com/articles/T-SQL/62867/) to generate all dates.
[**SQL Fiddle**](http://sqlfiddle.com/#!6/3c693/1/0)
```
;WITH E1(N) AS(
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION AL... | You need a tally table with "running numbers". This may be a function (I posted one shortly here: <https://stackoverflow.com/a/32096945/5089204>) or a physical table (I posted an example here: <https://stackoverflow.com/a/32474751/5089204>) or a CTE to do this "on the fly" (the table example does it this way).
If you ... | Split row into several with SQL statement | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm using a v12 server in Azure SQL Database, and I have the following table:
`CREATE TABLE [dbo].[AudienceNiches](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[WebsiteId] [nvarchar](128) NOT NULL,
[VisitorId] [nvarchar](128) NOT NULL,
[VisitDate] [datetime] NOT NULL,
[Interest] [nvarchar](50) NULL,
[Gender] [float] NULL,
[... | The best index for this query is a composite index on these columns, in this order:
* WebsiteId
* VisitDate
* Interest
* VisitorId
This allows the query to be completely answered from the index. SqlServer can range scan on (`WebsiteId`, `VisitDate`) and then exclude null `Interest` and finally count distinct `Visitor... | It's difficult for me to write SQL without having the data to test against, but see if this gives the results you're looking for with a better execution time.
```
SELECT interest, count(distinct visitorid)
FROM audienceNiches
WHERE WebsiteId = @websiteid
AND VisitDate between @startdate and @enddate
AND interest is no... | How to speed up current query with index | [
"",
"sql",
"sql-server",
"t-sql",
"indexing",
"azure-sql-database",
""
] |
I have a table called `results` with 5 columns.
I'd like to use the `title` column to find rows that are say: `WHERE title like '%for sale%'` and then listing the most popular words in that column. One would be `for` and another would be `sale` but I want to see what other words correlate with this.
Sample data:
```... | You can extract words with some string manipulation. Assuming you have a numbers table and that words are separated by single spaces:
```
select substring_index(substring_index(r.title, ' ', n.n), ' ', -1) as word,
count(*)
from results r join
numbers n
on n.n <= length(title) - length(replace(title, ... | You can use ExtractValue in some interesting way. See SQL fiddle here: <http://sqlfiddle.com/#!9/0b0a0/45>
We need only one table:
```
CREATE TABLE text (`title` varchar(29));
INSERT INTO text (`title`)
VALUES
('cheap cars for sale'),
('house for sale'),
('cats and dogs for sale'),
('iphones and andr... | How to find most popular word occurrences in MySQL? | [
"",
"mysql",
"sql",
"denormalization",
""
] |
i want to ask, does exist some way to use selected value from leftjoin table, into round function as decimal parameter.
For example.: `ROUND(sum(stats_bets_hourly.turnover_sum / currencies.rate ), 2) AS turnover_sum`
Should be: `ROUND(sum(stats_bets_hourly.turnover_sum / currencies.rate ), currencies.comma) AS turnov... | Yes, of course you can use a column instead of the numeric literal in ROUND.
That's easy to demonstrate:
```
select round(123.4567, pos) from (select 2 as pos) x;
```
In your case which is
```
ROUND(sum(stats_bets_hourly.turnover_sum / currencies.rate ), currencies.comma)
```
there must be just one `currencies.com... | Yes, you can do so as long as it is an integer number. | Mysql query - round() function | [
"",
"mysql",
"sql",
""
] |
I have:
```
TABLE MESSAGES
message_id | conversation_id | from_user | timestamp | message
```
I want:
```
1. SELECT * WHERE from_user <> id
2. GROUP BY conversation_id
3. SELECT in every group row with MAX(timestamp) **(if there are two same timestamps in a group use second factor as highest message_id)** !!!
4.... | Try below sql to achieve your purpose by group by twice.
```
select m.*
from
Messages m
-- 3. and then joining to get wanted output columns
inner join
(
--2. then selecting from this max timestamp - and removing duplicates
select conversation_id, max(timestamp), message_id
from
(
-- 1. first se... | Your query is based on non-standard use of `GROUP BY` (I think SQLite allows that only for compatibility with MySQL) and I'm not at all sure that it will produce determinate results all the time.
Plus it uses `MAX()` on concatenated columns. Unless you somehow ensure that the two (concatenated) columns have fixed widt... | sqlite3 query by max and filter by second factor | [
"",
"android",
"sql",
"database",
"sqlite",
""
] |
I'm trying to optimise a select (cursor in pl/sql code actually) that includes a pl/sql function e.g.
```
select * from mytable t,mytable2 t2...
where t.thing = 'XXX'
... lots more joins and sql predicate on various columns
and myplsqlfunction(t.val) = 'X'
```
The myplsqlfunction() is very expensive, but is only ... | You could specify a bunch of hints to force a particular plan. But that would almost assuredly be more of a pain than restructuring the code.
I would expect that what you really want to do is to [associate non-default statistics with the function](http://www.oracle-developer.net/display.php?id=426). If you tell Oracle... | You can use CTE like:
```
WITH X as
( select /*+ MATERIALIZE */ * from mytable t,mytable2 t2...
where t.thing = 'XXX'
... lots more joins and sql predicate on various columns
)
SELECT * FROM X
where myplsqlfunction(t.val) = 'X';
```
Note the Materiliaze hint. CTEs can be either inlined or materialized(into T... | can oracle hints be used to defer a (pl/sql) condition till last? | [
"",
"sql",
"oracle11g",
""
] |
Can anybody help me to get a result form multiple SQL requests:
```
SELECT *
(COUNT(*) AS Records FROM wp_posts WHERE post_type='news' AND post_status='publish') as News,
(COUNT(*) AS Records FROM wp_posts WHERE post_type='promotion' AND post_status='publish') as Promos,
(COUNT(*) AS Records FROM wp_posts WHERE post_t... | There is no need for subqueries at all:
```
SELECT
SUM(CASE WHEN post_type='news' THEN 1 ELSE 0 END) AS News,
SUM(CASE WHEN post_type='promotion' THEN 1 ELSE 0 END) AS Promos,
SUM(CASE WHEN post_type='contact' THEN 1 ELSE 0 END) AS Contacts
FROM wp_posts
WHERE post_status='publish';
```
or even shorter:
```
S... | Use **UNION ALL** to combine the queries (they need to have the same number of columns)
```
SELECT * FROM (
SELECT 1
UNION ALL
SELECT 2
)
``` | Bind multiple queries into one result | [
"",
"mysql",
"sql",
""
] |
I have two tables namely tbl\_votes and tbl\_candidates:
tbl\_votes: contains the ff column:
```
voteID president vicePresident secretary treasurer rep1 rep2 rep3
1 1 3 9 12 15
2 1 4 6 ... | ```
SELECT fName||' '||mName||' '||lName, votes FROM (
SELECT a.idcandidate, COUNT(b.idcandidate) votes
FROM tbl_candidates a
LEFT JOIN (
SELECT president idcandidate from tbl_votes
UNION ALL
SELECT vicePresident idcandidate from tbl_votes
UNION ALL
SELECT secretary idcandidate from tbl_votes
UNION ALL
SELECT treasurer... | Whereas you *could* approach this with a `CROSS JOIN` (but a different one than you propose) and appropriate aggregation of the results, that's a poor approach that would not scale well. Of course, there are no really good approaches when you are saddled with a crummy data model, as you are.
There are several ways to ... | How to select multiple columns with 1 column with count | [
"",
"mysql",
"sql",
""
] |
## GTS Table
```
CCP months QUART YEARS GTS
---- ------ ----- ----- ---
CCP1 1 1 2015 5
CCP1 2 1 2015 6
CCP1 3 1 2015 7
CCP1 4 2 2015 4
CCP1 5 2 2015 2
CCP1 6 2 2015 2
CCP1 7 3 2015 3
CCP1 8 3 2015 ... | Following solution assumes there are always 3 rows per quarter (only the last quarter might be partial), single SELECT, no recursion :-)
```
WITH sumQuart AS
(
SELECT *,
CASE
WHEN ROW_NUMBER() -- for the 1st month in a quarter
OVER (PARTITION BY CCP, Years, Quart
ORDER... | Another method that uses the `EXP(SUM(LOG()))` trick and only window functions for the running total (no recursive CTEs or cursors).
Tested at **[dbfiddle.uk](http://dbfiddle.uk/?rdbms=sqlserver_2016&fiddle=e0d042ae452d9c0121d7ca570807d9c6)**:
```
WITH
ct AS
( SELECT
ccp, years, quart,
q2 = ro... | Running Multiplication in T-SQL | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2012",
"sql-server-2014",
""
] |
I'm trying to limit my rows based on column values, but having difficulty getting the syntax right.
Given:
```
create table acctprefs (acctid char(5),
prefcode char(3));
insert into acctprefs values ('10000', 'ABC');
insert into acctprefs values ('10000', 'DEF');
insert into acctprefs values ... | One approach is aggregation with a `having` clause:
```
select ap.acctid
from acctprefs ap
group by ap.acctid
having sum(case when ap.prefcode = 'ZZZ' then 1 else 0 end) = 0;
```
The `having` clause counts the number of ZZZ for each account . . . and returns only those with zero. | One way of doing it is using `minus`.
```
select acctid
from acctprefs
where arefcode <> 'ZZZ'
minus
select acctid
from acctprefs
where arefcode = 'ZZZ'
``` | Oracle SQL: Distinct list of results based row not having column value | [
"",
"sql",
"oracle",
"having-clause",
""
] |
I am using Rails 4.2 with PostgreSQL. I have a `Product` model and a `Purchase` model with `Product` `has many` `Purchases`. I want to find the distinct recently purchased products. Initially I tried:
```
Product.joins(:purchases)
.select("DISTINCT products.*, purchases.updated_at") #postgresql requires order column i... | Use a subquery and add a different `ORDER BY` clause in the outer `SELECT`:
```
SELECT *
FROM (
SELECT DISTINCT ON (pr.id)
pu.updated_at, pr.*
FROM Product pr
JOIN Purchases pu ON pu.product_id = pr.id -- guessing
ORDER BY pr.id, pu.updated_at DESC NULLS LAST
) sub
ORDER BY updated_at ... | So building on @ErwinBrandstetter answer, I finally found the right way of doing this. The query to find distinct recent purchases is
```
SELECT *
FROM (
SELECT DISTINCT ON (pr.id)
pu.updated_at, pr.*
FROM Product pr
JOIN Purchases pu ON pu.product_id = pr.id
) sub
ORDER BY updated_at DESC ... | Rails - Distinct ON after a join | [
"",
"sql",
"ruby-on-rails",
"postgresql",
"greatest-n-per-group",
"ruby-on-rails-4.2",
""
] |
I am fetching table-names from particular database like this
```
SELECT name FROM sys.Tables where name like 'some pattern'
Output :
Name
sampletable_123,
sampletable_456,
sample_789.
```
It can return more than one row like above output. How to fetch row one by one?
Because I want to find out column-name/date fro... | Thanks SubqueryCrunch and Sergio Internicola for ur help.@Sergio Internicola, ur logic is right.I think curser take time.I modified SubqueryCrunch's query.It is working fine with me.
```
DECLARE @SQL NVARCHAR(4000)
SET @SQL = ' '
SELECT
@SQL += 'IF EXISTS(SELECT TOP 1 udate FROM ' + name + ' WHERE DATEDIFF(day... | You can use a cursor on the above select, and fetch one row at a time.
For each row, you can retrieve the first row of the table and decide to drop it or not.
```
DECLARE @TABLES CURSOR
DECLARE @MYNAME VARCHAR(100)
SET @TABLES CURSOR FOR
SELECT name FROM sys.Tables WHERE name LIKE 'sample%'
OPEN @TABLES
WHILE 1 ... | How to fetch row one by one in sql | [
"",
"sql",
"asp.net",
"sql-server",
""
] |
I have a table like this:
```
DROP TABLE IF EXISTS `locations`;
CREATE TABLE IF NOT EXISTS `locations` (
`tenant_id` int(11) NOT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`waypoint_id` int(11) NOT NULL,
`material` int(11),
`price` decimal(10,2) NOT NULL,
PRIMARY KEY (`tenant_id`,`id`),
UNIQUE KEY `id` ... | Your query seems to be wrong. It should be like this:
```
UPDATE locations
SET waypoint_id=23,
material=19,
price=22.22,
unit_id=1
WHERE tenant_id=3 AND id = 54;
```
**EDIT:**
You need to check that your table doesn't have the waypoint\_id as 23 and material as 19 as you have made it as unique. If there is any dupl... | ```
UNIQUE KEY(`waypoint_id`, `material`)
```
So when you **do** have that constraint, you can not have 2 rows that have same combination for those 2 values. So you cant have two rows with 23 as waypoint\_id and 19 as material, simple as that.
That's what unique means. That combination has to be unique whether you up... | I can't update a table that has two unique keys | [
"",
"mysql",
"sql",
""
] |
So i have a MySQL table that contains 2 fields - deviceID and jobID. Below is a sample of what the table looks like with Data in it:
```
+----------------------+----------------------+
| deviceID | jobID |
+----------------------+----------------------+
| f18204efba03a874bb9f | be83dec5d120c... | You need to provide the correct value for jobID. Presently you are providing the value of deviceID in jobID which is not matching and hence returing 0 rows.
```
SELECT Count(deviceID) FROM pendingCollect
WHERE jobID='49ed54279fb983317051' AND deviceID='49ed54279fb983317051'
^^^^^^^^^^^^^^^^^^^^^^^
```
Th... | This is because of the `AND` operator. `AND` means both conditions must be true. Instead of `AND`, use `OR` operator.
```
SELECT Count(deviceID)
FROM pendingCollect
WHERE jobID = '49ed54279fb983317051' OR deviceID = '49ed54279fb983317051'
``` | Count returns 0 for a column that exists | [
"",
"mysql",
"sql",
""
] |
I want to run a query on `MySql version 5.1.9` that returns me only top two (order by JoiningDate) of selected Dept.
For example, my data is like:
```
+-------+------------------------------------------+----------+------------+
| empid | title | Dept | JoiningDate|
+-------+----... | In mysql you can use user defined variables to achieve you desired results
```
SELECT
t.empid,
t.title,
t.Dept,
t.JoiningDate
FROM
(
SELECT
*,
@r:= CASE WHEN @g = b.Dept THEN @r + 1 ELSE 1 END rounum,
@g:= b.Dept
FROM (
SELECT *
FROM table1
CROSS JOIN (SELECT @r:= NULL,@... | Use a correlated sub-select to count number of rows with same date but a later JoiningDate. If less than 2, return the row.
```
select empid, title, Dept, JoiningDate
from tablename t1
where (select count(*) from tablename t2
where t2.Dept = t1.Dept
and t2.JoiningDate > t1.JoiningDate) < 2
``` | How to get Latest N Records of selected Group | [
"",
"mysql",
"sql",
"date",
"group-by",
"sql-order-by",
""
] |
So far i was using
```
IF OBJECT_ID(''tempdb..#tempTable'') IS NOT NULL -- dropping the temp table
DROP TABLE #tempTable
```
**Is there a way in which** I could use the same statement for a table which is not a temp one?
Tried like this and it didn't work:
```
IF OBJECT_ID(''myOwnDb.dbo.myTable'') IS NOT NULL -... | Strings in MS SQL server should be enclosed in **single** quotes.
So neither `OBJECT_ID(''myOwnDb.dbo.myTable'')` nor `OBJECT_ID("myOwnDb.dbo.myTable")` will work.
But `OBJECT_ID('myOwnDb.dbo.myTable')` will work perfectly. | In addition to what other users have suggested wrt `Object_ID` which is fine, you can explore below method to detect if table exist or not using `INFORMATION_SCHEMA`
```
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = N'Your Table Name')
BEGIN
Drop table <tablename>
END
``` | drop table #temp vs drop myTable if it's not null | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
"sql-server-2012",
""
] |
I have a database of users who pay monthly payment. I need to check if there is continuity in these payments.
For example in the table below:
```
+---------+------------+
| user_id | date |
+---------+------------+
| 1 | 2015-02-01 |
| 2 | 2015-02-01 |
| 3 | 2015-02-01 |
| 1 | 2015-03-01 ... | I have written a simple query for this but I realize that it's not the best solution. Other solutions are still welcome.
```
SELECT user_id,
MIN(date) AS min_date,
MAX(date) AS max_date,
COUNT(*) AS no_of_records,
round((MAX(date)-MIN(date))/30.4+1,0) AS months,
(months-no_of_records... | From my experience, you cannot just work with paid in table to fill the gaps. If in case all of your user does not pay a specific month, it is possible that your query leaves that entire month out of equation.
This means you need to list all dates from Jan to Dec and check against each user if they have paid or not. W... | Date continuity in a database (find missing date gaps) | [
"",
"sql",
"ms-access",
"vba",
"gaps-and-islands",
""
] |
I have the following problem:
Suppose there is a table `EMP` with employees data.
The columns that we are interested in are `DeptID` and `ManagerID`.
I have a list of (say) 50 records in the following format -
deptId1 , managerid1 so on
What is the most efficient way of doing this in sql?
For example, if I was onl... | You can use `= ANY`:
**[SqlFiddleDemo](http://sqlfiddle.com/#!4/bbcd1/2/0)**
```
SELECT *
FROM EMP
WHERE (ManagerID, DeptId) = ANY ((1,1), (2,4));
```
or `IN` + `subquery`:
```
SELECT *
FROM EMP
WHERE (ManagerID, DeptId) IN (SELECT 1 AS col1, 1 AS col2 FROM dual
UNION ALL SELECT 2... | ```
select
*
from
emp
where
(managerid, departmentid) in (
(1, 2),
(2, 3)
)
``` | Efficient sql query to find a composite key in a table? | [
"",
"sql",
"oracle11g",
""
] |
I have a table that probably resulted from a listagg, similar to this:
```
# select * from s;
s
-----------
a,c,b,d,a
b,e,c,d,f
(2 rows)
```
How can I change it into this set of rows:
```
a
c
b
d
a
b
e
c
d
f
``` | In redshift, you can join against a table of numbers, and use that as the split index:
```
--with recursive Numbers as (
-- select 1 as i
-- union all
-- select i + 1 as i from Numbers where i <= 5
--)
with Numbers(i) as (
select 1 union
select 2 union
select 3 union
select 4 union
select 5
)
select spli... | [SQL Fiddle](http://sqlfiddle.com/#!4/b61675/5)
**Oracle 11g R2 Schema Setup**:
```
create table s(
col varchar2(20) );
insert into s values('a,c,b,d,a');
insert into s values('b,e,c,d,f');
```
**Query 1**:
```
SELECT REGEXP_SUBSTR(t1.col, '([^,])+', 1, t2.COLUMN_VALUE )
FROM s t1 CROSS JOIN
TABLE
(
CAST
(
... | Undo a LISTAGG in redshift | [
"",
"sql",
"amazon-redshift",
""
] |
I have `DS.UnitPrice` and `Ord.Qty` that I need to multiply. Then take the sum of that and add up each of those if there is multiple `LineTotal`'s.
From there, take the subtotal and multiply it by `1.1` (tax
of 10%) and get the orders total.
I had issues with `SubTotal`, but got it to work. But `TotalPrice` still giv... | The problem is that you are referring to a column alias `subtotal` in the definition of total. And, your `JOIN` conditions are all wrong.
If you want the totals per order:
```
SELECT Ord.OrderId,
SUM(DS.UnitPrice * Ord.Qty) AS SubTotal,
SUM(DS.UnitPrice * Ord.Qty * 1.1) AS TotalPrice
FROM Orders Ord JOI... | you can do this one :
```
SELECT *, SUM(DS.UnitPrice*Ord.Qty) as LineTotal ,SUM(LineTotal) as SubTotal,SUM(SubTotal*1.1) as TotalPrice
FROM (Orders Ord, Donuts DS, Customers Cust)
LEFT JOIN Customers ON (Cust.CustID = Ord.OrderID)
LEFT JOIN Donuts ON (DS.DonutID = Ord.DonutID)
``` | Multiple SUM's in one SELECT | [
"",
"mysql",
"sql",
""
] |
I have a `SQL` table like this
```
col1 col2 col3
1 0 1
1 1 1
0 1 1
1 0 0
0 0 0
```
I am expecting output as like this
```
col1 col2 col3 NewCol
1 0 1 SL,PL
1 1 1 SL,EL,... | The issue with your code example is that when all columns are 0 then the length is 0 and the substring function will throw an error.
Use `nullif` to fix it: `substring(NewCol, 1, len(nullif(NewCol,'')) - 1) AS NewCol` | You could also change to appending the delimiter on the front and use [`STUFF`](https://msdn.microsoft.com/en-us/library/ms188043.aspx).
`STUFF('',1,1,'')` will return `NULL` rather than an error.
```
WITH
Employee(col1, col2, col3) AS (
SELECT 1,1,1 UNION ALL
SELECT 0,0,0
),
CTE AS (
SELECT col1, col2, col3,
... | Concatenate SQL table rows with conditions in single text | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
Will the result of this queries be able to join without multiplying to each other.
```
Select StudID, StudName, StudYear from tbl_students where StudYear='Third Year';
Select StudID, StudName, StudYear from tbl_students where StudYear='Second Year';
Select StudID, StudName, StudYear from tbl_students where StudYear='F... | To achieve your requirement you must have some id kind of thing to join, so used row number else you will one to many to many resutls
Working in SQL Server. So give it a try in MYSQL.
```
CREATE TABLE #STUDENT(ID INT, NAME VARCHAR(10), STUDENT_YEAR INT);
INSERT INTO #STUDENT VALUES(1,'FOO1',1);
INSERT INTO #STUDENT V... | Ok changed my answer to use subqueries and treat each subquery as a table with its own aliased columns. This does not produce the exact results you wanted this will produce nulls in the other 6 columns that are not filled in. That being said I believe this is about as close are you are going to get to doing what you wa... | Will it be possible to join table with itself | [
"",
"mysql",
"sql",
""
] |
I am using PostgreSQL to write an SQL query to select from the same sql results twice. For example,
```
SELECT a.id, b.id
FROM
(SELECT * FROM tableA) as a,
(SELECT * FROM tableA) as b
WHERE a.id = b.id+1
```
As you can see the following SQL query has been executed twice:
```
SELECT * FROM tableA
```
Is ... | Common Table Expression:
```
with cte as
(SELECT * FROM tableA)
select * from cte where...
```
So you don't have to write the same stuff twice. Don't know if its executed once or severel times though... | A CTE solves your problem. But it is likely that the `lead()` function would as well . . . and with better performance:
```
SELECT a.*
FROM (SELECT a.id, lead(a.id) over (order by a.id) as b_id
FROM tableA a
) a
WHERE id = b_id;
```
Or, for something that will work with duplicates:
```
SELECT a.id, a.id +... | Postgresql: How to select from the sql results twice | [
"",
"sql",
"postgresql",
"query-optimization",
""
] |
Hi guys I'm having problems with a sql query, look, this is my scenario:
I have an students table and a table where I store dates when students enter or leave the school, so I want to get the nearest date to a given date for every student, I can't find the way to do this.
```
Students Data:
|idstudent|name |
------... | Using the proprietary `distinct on ()` is usually faster in Postgres than using window functions.
Building on Gordon's idea with the abs():
```
select distinct on (s.idstudent) s.*, sd.date_, sd.type
from students s
join students_dates sd on s.idstudent = sd.idstudent
order by s.idstudent, abs(sd.date_ - date '2015... | Use `DATEDIFF` to get difference between dates, get `ABS` value. Then sort by `ABS(DATEDIFF())` and get top record. | Get closest date to given date for a group of records | [
"",
"sql",
"postgresql",
"date",
""
] |
Recently I have started learning `Oracle-sql`. I know that with the help of `DELETE` command we can delete a particular row(s). So, Is it possible to delete entire data from a particular column in a table using only `DELETE` command. (I know that using `UPDATE` command by setting null values to entire column we can ach... | **[DELETE](http://docs.oracle.com/cd/B12037_01/appdev.101/b10807/13_elems014.htm)**
> The DELETE statement **removes entire rows** of data from a specified
> table or view
If you want to "remove" data from particular column update it:
```
UPDATE table_name
SET your_column_name = NULL;
```
or if column is `NOT NULL`... | In SQL, `delete` deletes rows not columns.
You have three options in Oracle:
* Set all the values to `NULL` using update.
* Remove the column from the table.
* Set the column to unused.
The last two use `alter table`:
```
alter table t drop column col;
alter table t set unused (col);
``` | Deleting entire data from a particular column in oracle-sql | [
"",
"sql",
"oracle",
"sql-delete",
""
] |
Is there an easier/more efficient way of doing the following WHERE conditions:
```
WHERE (Field LIKE %entry% OR Field2 LIKE %entry%)
AND (Field LIKE %entry2% OR Field2 LIKE %entry2%)
``` | Please refer following [link](https://dev.mysql.com/doc/refman/5.1/en/fulltext-boolean.html) as well:
```
SELECT *
FROM mytable
WHERE MATCH(filed, field2) AGAINST ('entry' IN NATURAL LANGUAGE MODE)
``` | ```
AND (Field LIKE %entry2% OR Field2 LIKE %entry2%)
```
this part is a part of
```
(Field LIKE %entry% OR Field2 LIKE %entry%)
```
You can omit it. | SQL: Where Field OR Field2 LIKE %entry% | [
"",
"mysql",
"sql",
""
] |
This question is regarding PLSQL - for improving the efficiency of the code and coding standards.
Any help, pointers, references or suggestions are highly appreciated.
**Question:**
I have a plsql procedure with an INPUT parameter `i_flag` which is of type `BOOLEAN`.
Based upon the value of this i\_flag( which can ... | You can create the same behavior in a single query using the logical `or` operator:
```
select a.user_id, a.user_name, a.dept_id, b.country
from user a , contact b
where a.user_id = b.user_id AND (i_flag = TRUE OR a.user_status IS NOT NULL)
```
Note, by the way, that implicit joins (having two tables in the `from` c... | First of all, if you want to use a boolean param in a SQL query, you have to substitute a sql-compatible type such as NUMBER, i.e. use 0 or 1 instead of FALSE or TRUE.
Second, while Mureinik's answer based on OR will work, Oracle will often give better performance if you use an alternative. One alternative is like thi... | PLSQL - Improving code efficiency | [
"",
"sql",
"oracle",
"select",
"plsql",
"plsqldeveloper",
""
] |
I have 2 tables
**1. User Master**
user\_id, user\_full\_name, user\_dob...so on
**2. Login Details**
login\_id, login\_user\_id, login\_time, login\_date, logout\_time
***Problem***
2nd table has n number of rows against User Master table id
I need to make a join but the condition is that it should show only last... | If you want the result for a single user, you could use a simple `INNER JOIN` combined with an `ORDER BY` and `TOP 1`:
```
SELECT TOP 1 user_full_name, login_time, login_date, logout_time
FROM Users INNER JOIN Logins ON
Users.user_id = Logins.user_id
WHERE
Users.user_id = @user_id
ORDER BY login_date DESC, login_t... | A common solution for this problem is to use the `row_number` window function and filter for rows with row number 1 in each partition (by user, ordered by date/time):
```
WITH UserDetails AS (
SELECT
*
, ROW_NUMBER() OVER (PARTITION BY login_user_id
ORDER BY login_date D... | How to get latest DETAIL entry against the MASTER entry? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"greatest-n-per-group",
""
] |
What I am trying to do, is to set beginning of time interval, if that is not correctly set into stored procedure. However, it somehow does not work very well..
This is my code:
```
CREATE PROCEDURE intervals_generator (IN start DATETIME, IN ending DATETIME, IN intervalis INT)
BEGIN
-- temp values
DECLARE nex... | If you work in [`DATE`s](https://dev.mysql.com/doc/refman/5.6/en/datetime.html) instead of strings, you can make use of MySQL's date [functions and operators](https://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html) and make everything a whole lot simpler... but not too simple because this is MySQL.
The p... | This statement is not doing what you expect:
```
SET new_start := year+' '+month+' '+day+' 00:00:00';
```
In MySQL, the `+` operator does addition. That's it, not concatenation.
I think you intend:
```
SET new_start := concat(year, ' ', month, ' ', day, ' 00:00:00');
```
I haven't looked at the rest of the logic t... | Changing datetime value in MySQL | [
"",
"mysql",
"sql",
"datetime",
""
] |
I have a table with a member's name, address, etc. and a time stamp of the last time the record was updated. I have a second table that holds updates to the member record, a holding table, until changes are approved by staff.
I have a query that returns data from the member table. I now need to check the updates table... | Here is a simple query that will help you return the most recent record:
```
--Only selects the top row with the most recent record
SELECT TOP 1 * FROM record
(
--Select rows with the same ID
SELECT name, address, city, state, zipcode, time_stamp
FROM Member
WHERE ID = 123
UNION ALL
SELECT name... | The union approach is a good idea, but you'd want to use the `row_number()` window function and not just top. Also, `union all` can be used instead of `union`. You don't care about duplicates between `A` and `B`, and `union all` will just perform better:
```
SELECT name, address, city, state, zipcode, time_stamp
FROM ... | Query to return values from table B when newer than record in Table A | [
"",
"sql",
"t-sql",
"select",
"sql-server-2005",
""
] |
Using SQL Server 2012
I have seen a few threads about this topic but I can't find one that involves multiple joins in the query. I can't create a VIEW on this database so the joins are needed.
The Query
```
SELECT
p.Price
,s.Type
,s.Symbol
, MAX(d.Date) Maxed
FROM AdventDW.dbo.FactPrices ... | If you want data for the maximum date, use `row_number()` rather than `group by`:
```
SELECT ts.*
FROM (SELECT p.Price, s.Type, s.Symbol, d.Date,
ROW_NUMBER() OVER (PARTITION BY s.Type, s.Symbol
ORDER BY d.Date DESC
) as seqnum
FROM Adve... | You should use a derived table since you really only want to group the `DateTimeKey` table to get the `MAX` date.
```
SELECT p.Price ,
s.Type ,
s.Symbol ,
tmp.MaxDate
FROM AdventDW.dbo.FactPrices p
INNER JOIN dbo.DimSecurityMaster s ON s.SecurityID = p.SecurityID
INNER JOIN
( SELECT MAX(d.Date) ... | Get Distinct results of all columns based on MAX DATE of one | [
"",
"sql",
"sql-server",
"max",
""
] |
I am trying to display multiple authors per title in a single column. At the moment there a repeating rows, due to the fact that some `Titles` have more than 1 `FirstName`. Is there a form of concatenation that can be used to resolve this and display all the authors in a single filed and perhaps separated by a comma.
... | You may inclde the concantenation logic within a CROSS APPLY
```
SELECT
Submission.Title
, CA.FirstNames
, Submission.Type
FROM Submission
CROSS APPLY (
SELECT
STUFF((
SELECT /* DISTINCT ??? */
', ' + r.FirstName
... | You can do this in your application logic as well.
But if you want to do this with a query. You should be able do something like this:
```
SELECT DISTINCT
sm.Title,
STUFF(
(SELECT ', ' + r.FirstName
FROM ResearcherSubmission rs
INNER JOIN Researcher r ON r.ResearcherID = rs... | display more than one value using a SQL query | [
"",
"sql",
"sql-server",
""
] |
My stored procedure has 3 parameters i'm passing `(@nameP, @idP, @dateP`)
and is inserting the data in a `#myTemp` table
then i use
```
select *
into dbo.realTable
from #myTemp
```
and then I want to filter out any data which already exists (in `dbo.FinalTable`)based on `dateP` and `idP`:
```
insert into ... | Basically you have used `not exists` which is absolutely correct. the problem in you query for next time is `@dateP`. If you pass same `@idP` but different `@dateP` then same `@idp` get created because your getting validate against @idp and `@dateP`. So how you protect that, think about your business scenario for dupli... | this inserts all rows from realtable do finaltable, where the combination of idP and dateP is NOT existing...(using a simple left join):
```
INSERT INTO dbo.FinalTable
SELECT *
FROM dbo.RealTable R
LEFT JOIN dbo.FinalTable T ON T.idP = R.idP
AND T.dateP = R.dateP
WHERE T.idP IS NULL
```
I would ... | insert into table and skip duplicates | [
"",
"sql",
"sql-server",
"stored-procedures",
"sql-server-2012",
""
] |
I require a piece of sql code which shows me the year part of a specific date, however the new year should start on november 1st.
for example the below two will bring me 2014 :
```
select DATEPART(year, '2014-10-01')
select DATEPART(year, '2014-11-01')
```
How I need the second one to return 2015 as the new year for... | Add two months and get the year part of it.
```
select datepart(year, dateadd(MONTH,2,'2014-10-01')), -- 2014
datepart(year, dateadd(MONTH,2,'2014-11-01')) -- 2015
``` | Assuming MS SQL Server...
```
SELECT DATEPART(YEAR, DATEADD(MONTH,2,'2014-11-01'))
``` | sql date for year start | [
"",
"sql",
"date",
""
] |
I would like to return table from plpgsql function.
Here is my code.
```
CREATE FUNCTION test() RETURNS my_table AS
$BODY$DECLARE
q4 my_table;
BEGIN
q4 := SELECT * FROM my_table;
RETURN q4;
END;$BODY$
LANGUAGE sql;
```
I am getting following error:
```
Error: ERROR: ... | ```
CREATE FUNCTION test()
RETURNS my_table AS
$BODY$
DECLARE
q4 my_table;
BEGIN
-- add brackets to get a value
-- select row as one value, as q4 is of the type my_table
-- and limit result to one row
q4 := (SELECT my_table FROM my_table ORDER BY 1 LIMIT 1);
RETURN q4;
END;$BODY$
-- change lan... | PostgreSQL has not table variables. So you cannot to return table via any variable. When you create any table, then PostgreSQL creates composite type with same name. But it isn't table type - it is composite type - record.
```
CREATE TABLE xx(a int, b int);
CREATE OR REPLACE FUNCTION foo()
RETURNS xx AS $$
DECLARE v ... | Returning set of rows from plpgsql function. | [
"",
"sql",
"postgresql",
"plpgsql",
""
] |
What I want to do is to convert multiple rows into a single row using case-when, but I get
> ORA-00979: not a GROUP BY expression
this is my query
```
SELECT P.APPDISPLAYNAME AS PLAYERNAME ,
CASE WHEN GS.SETNUMBER = 1 THEN SS.SETSCORE END AS set1,
CASE WHEN GS.SETNUMBER = 2 THEN SS.SETSCORE END AS s... | First, you should learn to use proper explicit `JOIN` syntax. Even Oracle now recommends its use.
Second, your `SELECT` needs aggregation functions. I would recommend something like this:
```
SELECT P.APPDISPLAYNAME AS PLAYERNAME ,
MAX(CASE WHEN GS.SETNUMBER = 1 THEN SS.SETSCORE END) AS set1,
MAX(CAS... | All the columns that appear in your `SELECT` clause must either be included in your `GROUP BY` clause, or else have some kind of [Aggregate function](http://docs.oracle.com/database/121/SQLRF/functions003.htm#SQLRF20035) applied.
In your case, if you want just one row to be returned, you should for example use a `MAX(... | Convert multiple rows in to single row in SQL using Case-When | [
"",
"sql",
"oracle",
""
] |
I have following `UPDATE` query, but something is wrong when executing.
I'm trying to update values in *table1* with values in table *import\_data*, but I need the id from table *ids*... So the table *ids* links *table1* and \*import Simple, isn't it?
```
UPDATE table1
INNER JOIN import_data ON (
import_data.id = ... | Try:
```
update table1 t1
inner join (
select idata.name, ids.link
from import_data idata
join ids on ids.id = idata.id
where ids.type = 'NORMAL'
) x
on x.link = t1.id
set t1.name = x.name
```
**Demo** [sqlfiddle](http://sqlfiddle.com/#!9/8c188/1) | I think it's depends on database you're using. The relevant post is answered here - [How can I do an UPDATE statement with JOIN in SQL?](https://stackoverflow.com/questions/1293330/how-can-i-do-an-update-statement-with-join-in-sql) | Updating values in one table based on another | [
"",
"mysql",
"sql",
""
] |
I have two tables; Savings and Spend. What I need is both of them rolled up into one row by Month & Year, and Site/Location.
Tables are setup as followed. Data is obviously cleansed and please ignore the lovely structure for dates.
Spend Table
```
Site# Region Total Spend Month Year
52 Region1 $589.01 8 2015
52 R... | I know that you said in a few places that you were having problems with a subquery, but this one seems to work fine for me:
```
SELECT sp.site#, sp.region,sp.month,sp.year,savingstotals.[total savings], sum([totalspend]) as [Total Spend]
FROM
spend sp
INNER JOIN
(SELECT site, region, month, year , sum([total savings]... | ```
select
([s_agg].[Month],
[s_agg].[Year],
[s_agg].[Site],
[s_agg].[Region],
[s_agg].[tot_sav],
[sp_agg].[tot_sp]
from (
select [s].[Month],
[s].[Year],
[s].[Site],
[s].[Region],
SUM([s].[Total Savings] [tot_sav]
FROM [Savings] AS [s]
GROUP BY
[s].[Month],
[s].[Year],
[s].[Site],
[s].... | SQL Aggregation issue | [
"",
"sql",
"sql-server",
"aggregate",
"aggregation",
""
] |
```
Dim dtIzvrsenja datetime
Private Sub chkDate_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkDate.CheckedChanged
If Me.chkDate.Checked Then
Me.dtpDate.CustomFormat = "dd.MM.yyyy"
Me.dtpDate.Enabled = True
dtIzvrsenja = dtpdate.value
... | In order to support that, you need to use the generic `Nullable(Of Date)` type rather than just `Date` (the VB alias for the `DateTime` type). Normally, only *reference type* variables (`Class` type variables) support null values. Since `Date` is a *value type* variable (`Structure`), it doesn't support null. `Nullable... | Use `Nullable`:
```
Dim nullableDateValue As New Nullable(Of Date) = Nothing
``` | Set date variable to null | [
"",
"sql",
"vb.net",
""
] |
I have used SQL CASE statement on an INT type of column of a table.
Following is the SQL table schema and query which is working fine.
**SQL Query**
```
CREATE TABLE #TEMP_A(ID BIGINT ,ACCEPTED INT)
INSERT INTO #TEMP_A VALUES(1,1)
INSERT INTO #TEMP_A(ID) VALUES(2)
INSERT INTO #TEMP_A(ID) VALUES(3)
INSERT INTO #TEMP_A... | try:
```
SELECT T.ID,T.ACCEPTED,
(CASE WHEN T.ACCEPTED IS NULL THEN 'NOT ACCEPTED' END) AS STATUS
FROM #TEMP_A T
``` | Use `IS NULL` to check for a `NULL` value. Try this query:
```
SELECT T.ID,T.ACCEPTED,
(CASE WHEN (T.ACCEPTED IS NULL) THEN 'NOT ACCEPTED' END) AS STATUS
FROM #TEMP_A T
``` | Why sql case is not working on null condition of int column | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I want to find the peak value across multiple time series concurrently, like the following. However to make this a little more complicated, I may have 20k+ entities with 200 data points each, so performance is important.
I only require the peak achieved across all entities. So for clarification, let's say my entities ... | If you need just the date of the maximum sum, then simple `GROUP BY` would be enough.
[SQL Fiddle](http://sqlfiddle.com/#!3/9cc27/2/0)
```
SELECT TOP(1)
dt
,SUM(Value) AS Total
FROM T
GROUP BY dt
ORDER BY Total DESC;
```
**Result**
```
dt Total
1900-01-03 24
``` | *here solution using dynamic query*
```
-- create temp table for data sample
IF OBJECT_ID('Tempdb..#test') IS NOT NULL
DROP TABLE #test
CREATE TABLE #test
(
[Date Time] DATE ,
Entity VARCHAR(1) ,
VALUE INT
)
INSERT INTO #test
( [Date Time], Entity, VALUE )
VALUES ( '1900-01-01... | Finding peaks across multiple time series | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
```
INSERT INTO clnt_reports_01 (r_id, cl_no, cl_no, servi, size, vol,
deliver_point, port_, a_port, road, term, compet, speed,
rcomments, stage, meetrating, username, user_status, kids,
hobbies, comments)
VALUES (1, 123123, "test", "test", "test", "test",
"test", "test", "test", "test", 1, "test", "test",
3, 5, ... | **EDIT:**
You have specified 21 columns and provided only 20 values so there is a mismatch.
`cl_no` seems to be repeated twice. Remove that.
---
You need to use single quotes instead of double for text
```
INSERT INTO clnt_reports_01 (
r_id,
cl_no,
servi,
size,
vol,
deliver_point,
port_,
a_port,
road,
term,
compe... | Qoute strings with `'` and **make sure there is the same number of column in both cases (20)**:
```
INSERT INTO clnt_reports_01 (r_id,cl_no,servi,size,vol,deliver_point,port_,a_port,road,term,compet,speed,rcomments,stage,meetrating,username,user_status,kids,hobbies,comments)
VALUES (1, 123123, 'test', 'test', 'test',... | Column count doesn't match value count at row | [
"",
"mysql",
"sql",
""
] |
I have a relatively straightforward sql query which refuses to execute on sqldeveloper, I've narrowed down the offending line to this -
```
and (b.date_updated > (sysdate MINUS 2) or a.date_updated > (sysdate MINUS 2))
```
This is a part of my `where` clause along with other statements.
I've visually counted the par... | `MINUS` is a set operator that operates on two sets, essentially the "opposite" of what `UNION` or `UNION ALL` does.
To subtract a number from a date (or another number) use `-`
This is documented in the chapter "Arithmetic operators" in the Oracle manual:
<https://docs.oracle.com/cd/E11882_01/server.112/e41084/ope... | `MINUS` is not legal syntax. Replace each `MINUS` with the actual operator `-`. | ORA-00907 Missing right parenthesis even when parenthesis are balanced | [
"",
"sql",
"oracle",
"syntax-error",
""
] |
I need to change a few values on my DB.
I forgot to set nullable to the table and it set to 0000-00-00 00:00:00 by default.
Now I need to convert that value in `NULL`.
The field type is Datetime.
How can I do it?
I try with the typical `Update table set field = NULL WHERE field = '0000-00-00 00:00:00';` but it doe... | You need to first make the column nullable:
```
ALTER TABLE mytable MODIFY COLUMN field DATETIME NULL;
```
And then update the values:
```
UPDATE mytable SET field = NULL WHERE field = '0000-00-00 00:00:00';
``` | From MySQL 5.7, SQL mode NO\_ZERO\_DATE makes this update impossible unless you firstly disable this restriction (for the duration of the transaction only).
```
SET sql_mode=(SELECT REPLACE(@@sql_mode,"NO_ZERO_DATE", ""));
UPDATE mytable SET field = NULL WHERE field = '0000-00-00 00:00:00';
``` | How to set to NULL a datetime with 0000-00-00 00:00:00 value? | [
"",
"mysql",
"sql",
"datetime",
"null",
"sql-update",
""
] |
I need to create a column which shows the difference between the average of two consecutive days of a table, I tried to do this with a CTE query:
```
with aggregate
as
(
select date
,y
,z
,avg(x) as vwap
from table a
where z = 1
group by date,y,z
)
select aggregate.date
,aggregate.v... | The problem was I think that for every join or aggregate in the final select the whole CTE was rerun. When I created a temporary table of the CTE results and than run my Inner join final query on that the speed increased by factor 10. | You can use new SQL analytic functions [SQL Lead()](http://www.kodyaz.com/t-sql/lead-function-in-sql-server-2012-for-next-value.aspx) and [Lag() function](http://www.kodyaz.com/t-sql/lag-function-in-sql-server-2012-for-previous-values.aspx) introduced with SQL Server 2012
Please check following SELECT statement
```
;... | sql self join CTE or other way | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I need a way to find out the number of days for each set of same IDs set. For example, if there are two rows of ID1 with the first date being the 1st and the second date the 4th, the calculation for the 1st would be Sept 4th - the Sept 1st (since the 4th is the next date for ID1) and the calculation for the 4th would b... | You are basically looking for `lead()` functionality. And, you don't have it, so you have to improvise. Here is a method using `cross apply`:
```
select t.*,
datediff(day, t.date, coalesce(n.date, getdate())
from table t outer apply
(select top 1 t2.date
from table t2
where t2.id = t.id and t2.... | Using a common table expression, you can arrange your table into a temporary view with a start date and end date for each ID record, like this: <http://sqlfiddle.com/#!3/af078/7>
```
with t1 (id, dt, ndx) as (
select id, dt, row_number() over (partition by id order by dt)
from id_dates
)
,
t2 (id, startdt, enddt) ... | Simple SQL Query for date ranges | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I want to replace all characters in a string to "\*" star character.
For example:
```
NAME_SURNAME : ANDREY KIMBELL
REPLACED : ****** *******
```
How can I do this in Oracle PL/SQL ? | You could use:
**[Demo](http://sqlfiddle.com/#!4/9eecb7d/7165/0)**
```
SELECT REGEXP_REPLACE('ANDREY KIMBELL', '\w', '*')
FROM dual
```
where `\w` is the Alphanumeric characters plus `_` equivalent of `[A-Za-z0-9_]`.
Or if only letters:
```
SELECT REGEXP_REPLACE('ANDREY KIMBELL1', '[[:alpha:]]', '*')
FROM dual
``` | you could to it like this
```
select regexp_replace('abdcde123fge','[A-Za-z]','*')
from dual;
```
This replaces everything in the range of a-z and A-Z with a \* | replace all characters in string | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
I'm quite novice to SQL, but here's what I'm trying to do:
I have 3 sql queries that return 3 different sets of results (students, staff, customer), the columns are all the same
```
id first name last name address zip group 1 group 2 group 3
```
each select statement for each group populates one of the group columns... | Try:
```
SELECT ID,
"FIRST NAME",
"LAST NAME",
ADDRESS,
ZIP,
MAX(CASE "GROUP TYPE" WHEN 'STUDENT' THEN 'STUDENT' END) "GROUP 1",
MAX(CASE "GROUP TYPE" WHEN 'STAFF' THEN 'STAFF' END) "GROUP 2",
MAX(CASE "GROUP TYPE" WHEN 'CUSTOMER' THEN 'CUSTOMER' END) "GROUP 3"
F... | You can try this:-
```
SELECT id, first_name, last_name, address, zip, MAX(group1), MAX(group2), MAX(group3)
FROM YOUR_TABLES
GROUP BY id, first_name, last_name, address, zip
``` | SQL union all but flag groups? | [
"",
"sql",
"sql-server",
""
] |
In DB2, I have this query to list numbers 1-x:
```
select level from SYSIBM.SYSDUMMY1 connect by level <= "some number"
```
But this maxes out due to `SQL20450N Recursion limit exceeded within a hierarchical query.`
How can I generate a list of numbers between 1 and x using a select statement when x is not known at ... | I found an answer based on [this post](https://stackoverflow.com/questions/14339369/how-to-generate-a-list-of-number-in-sql-as-it-was-a-list-of-comprehension):
```
WITH d AS
(SELECT LEVEL - 1 AS dig FROM SYSIBM.SYSDUMMY1 CONNECT BY LEVEL <= 10)
SELECT t1.n
FROM (SELECT (d7.dig * 1000000) +
(d6.dig *... | That's how I usually create lists:
For your example
```
numberlist (num) as
(
select min(1) from anytable
union all
select num + 1 from numberlist
where num <= x
)
``` | select statement to list numbers in range | [
"",
"sql",
"db2",
""
] |
I'm trying to do an INNER JOIN of a few tables, but with certain condition:
I have the CONTACTS table:
```
code contact_type name email
----------------------------------------------------------------------------
1 P AAAAAAAA ... | I suggest you to use this query:
```
SELECT
CASE
WHEN CONTACT_TYPE = 'C' THEN
(SELECT Name FROM CLIENTS c WHERE c.Code = co.Code)
WHEN CONTACT_TYPE = 'P' THEN
(SELECT Name FROM PROVIDERS p WHERE p.Code = co.Code)
END AS [PROVIDER/CLIENT NAME],
CONTACT_TYPE, EMAIL
F... | You can try to do it with union:
```
SELECT p.Name AS [Provider/Client Name] ,
c.Contact_Type ,
c.Email
FROM contacts c
INNER JOIN providers p
ON c.code = p.code
WHERE c.Contact_Type = 'P'
UNION
SELECT cl.Name AS [Provider/Client Name] ,
c.Contact_Type ,
c.Email
FR... | How to use a inner join with 2 conditions in the same column | [
"",
"sql",
"sql-server",
"sql-server-2008",
"inner-join",
""
] |
I have a query that I need to add a column to. I can find many similar examples but nothing quite works right for this situation. There could be infinite CategoryIDs and I need to add the Sum(IsOutage) grouped by CategoryID. This is some sample data:
[ AS TotalIssues ,
AVG(DATEDIFF(MI, i.StartDate, i.ResolvedDate)) AS AvgDuration
FROM ... | You can use conditional aggregation. Also, you shouldn't `group by` totaloutages
```
SELECT
c.CategoryID
, c.Name
, COUNT(i.IssueID) AS TotalIssues
, AVG(DATEDIFF(MI, i.StartDate, i.ResolvedDate)) AS AvgDuration
,sum(case when IsOutage = 1 then 1 else 0 end) AS TotalOutages
FROM dbo.hdCategories AS c INNER JOIN
db... | : Select query with sum() as subquery | [
"",
"sql",
"sql-server-2008",
""
] |
# Problem
We are trying to understand why executing the same code by calling an stored procedure versus executing the store procedure contents in a query window is showing very different execution times but returns exactly the same result set of 183 rows.
# Test1
Executing the following SP from SSMS takes 5 minutes ... | There's several things that affect query plan creation in SQL Server which might cause really strange things seem to happen.
1. The plan for stored procedure is (normally) created in the first execution, using the parameters from that time. That plan is saved and used for all the future executions, even if the paramet... | * [Source](https://stackoverflow.com/questions/440944/sql-server-query-fast-but-slow-from-procedure)
Difference between running a query in a batch of scripts in SSMS vs running a query in a Stored Procedure is at least in two way:
1. Before creating your SP use `SET ANSI_NULLS ON`.
2. Use inner variable instead argum... | Executing same code via exec SP versus exec SP code in query window report same results but different execution times | [
"",
"sql",
"sql-server",
""
] |
I've been trying to write this query for 1 hour, but the SQL Developer always throws an error.
```
SELECT d.driver_name, COUNT(*) AS cnt
FROM Drivers d
JOIN Fastest_laps fl ON d.ID_driver = fl.ID_driver
GROUP BY d.driver_name
HAVING cnt = MAX(cnt);
```
> 904. 00000 - "%s: invalid identifier"
>
> Error at last... | Use a window function:
```
SELECT driver_name, cnt
FROM (SELECT d.driver_name, COUNT(*) AS cnt,
MAX(COUNT(*)) OVER () as MAXcnt
FROM Drivers d JOIN
Fastest_laps fl
ON d.ID_driver = fl.ID_driver
GROUP BY d.driver_name
) d
WHERE cnt = MAXcnt;
```
You can also express ... | Try this. I ordered by `cnt` in descending order. And then selected the top row from it. You can edit the query as `rownum <=2` to get the top 2 rows and so on.
```
with tbl1 as
(SELECT d.driver_name as driver_name, COUNT(*) AS cnt
FROM Drivers d
JOIN Fastest_laps fl ON d.... | Invalid identifier error, Oracle | [
"",
"sql",
"database",
"oracle",
""
] |
Table :
```
schedule_id job_id next_run_date next_run_time
------------------------------------------------------
221 D23EA7B2 20151005 90000
222 18EDFB21 20151020 90000
242 90283725 20151001 170000
239 4B69C670 20151011 900... | Assuming both are `varchar`, try this:
```
SELECT schedule_id, job_id,
CONVERT(datetime, next_run_date, 112)
+ CONVERT(time,
SUBSTRING(next_run_time, 1, LEN(next_run_time) - 4) + ':'
+ LEFT(RIGHT(next_run_time, 4), 2) + ':'
+ RIGHT(next_run_time, 2),
... | Here is one way to do it:
```
-- Create sample table and data
CREATE TABLE tbl (
next_run_date char(8),
next_run_time varchar(6)
)
INSERT INTO tbl VALUES
(20151005, 93020),
(20151001, 170000)
```
using cte1 to pad next\_run\_time with a leading zero if needed,
and using cte2 to break the string to a "normal" ti... | How to Combine dates and time in separate fields in SQL | [
"",
"sql",
"sql-server",
"date",
"ssrs-2008",
""
] |
(Editing my post with data and expected result as per replies.)
I have a table which looks as follows. I would like to compute the difference in `Score` between two adjacent records.
```
ID TimeStamp Score
1002010 9/26/2015 11:24:08 PM 32
1002010 9/28/2015 10:12:57 PM 38
```
This i... | You can use `lead` to get the value from the next row and use it for subtraction. Note that this function is available in sql server 2012 and later versions.
If you need `null` to be the result when there is no leading row, remove the `isnull` condition.
```
SELECT
ID,
Score,
ISNULL(convert(int, lead(Score) over(part... | You can implement `ROW_NUMBER()` in place of `lead/lag` if you are using pre-2012 SQL Server:
```
SELECT
[current].ID,
[current].Score,
ISNULL(convert(int,[next].Score), 0) - convert(int,[current].Score)
FROM
(Select *,ROW_NUMBER() OVER (ORDER BY ID,TimeStamp) as rn from RiskPredLog) AS [current]
LEFT JOIN... | Getting difference of value between two adjacent records in SQL Server | [
"",
"sql",
"sql-server",
""
] |
I have a table `issue` with following structure:
```
+----+---------+-------------+------------+
| id | project | new_status | updated_at |
+----+---------+-------------+------------+
| 1 | 1 | New | 12:41:18 |
| 1 | 1 | In progress | 12:47:43 |
| 1 | 1 | Resolved | 17:05:29 |
+-... | Since you already have some examples of doing it with lead() functions (which are definitely database specific), here's a different option: <http://sqlfiddle.com/#!15/497de/18>
```
with t1 (id, project, new_status, updated_at, ndx) as (
select id, project, new_status, updated_at,
row_number() over (partition by id... | I write this query on the fly so it is not tested:
```
SELECT id, project, new_status, (updated_at - nextUpdate) AS time_diff
--or CAST((updated_at - nextUpdate) AS time) AS time_diff
FROM (
SELECT *,
LEAD(updated_at) OVER (PARTITION BY project ORDER BY updated_at) AS nextUpdate... | SELECT query that uses data from another row | [
"",
"sql",
"postgresql",
"window-functions",
""
] |
Given a table in Google BigQuery:
```
User Timestamp
A TIMESTAMP(12/05/2015 12:05:01.8023)
B TIMESTAMP(9/29/2015 12:15:01.0323)
B TIMESTAMP(9/29/2015 13:05:01.0233)
A TIMESTAMP(9/29/2015 14:05:01.0432)
C TIMESTAMP(8/15/2015 5:05:01.0000)
B TIMESTAMP(9/29/2015 14:06:01.0233)
A TIMESTAMP(9/... | Here is an efficient succinct way to do it that exploits the ordered structure of timestamps.
```
SELECT
user,
MAX(per_hour) AS max_event_per_hour
FROM
(
SELECT
user,
COUNT(*) OVER (PARTITION BY user ORDER BY timestamp RANGE BETWEEN 60 * 60 * 1000000 PRECEDING AND CURRENT ROW) as per_hour,
timestamp... | Try below for GBQ. Haven't tested much, but looks workable to me
```
SELECT
User, Max(events) as Max_Events
FROM (
SELECT
b.User as User,
b.Timestamp as Timestamp,
COUNT(1) as Events
FROM [your_dataset.your_table] as b
JOIN (
SELECT User, Timestamp
FROM [your_dataset.your_table]
) as... | BigQuery: Computing aggregate over window of time for each person | [
"",
"sql",
"aggregate-functions",
"google-bigquery",
"window-functions",
""
] |
I got a lookup list table of valid US state abbreviations and a source table:
**States** lookup and **Source** tables respectively
```
+-------+ +-----------------+
|States | |ID | Location |
+=======+ +=================+
| AK | | 1 | Madrid |
--------- -------------------
| AL | | 2 |... | Since nobody has suggested using NULLIF i might as well throw that in.
```
DECLARE @Location TABLE (Id INT, Location VARCHAR(MAX))
DECLARE @States TABLE (States VARCHAR(MAX))
INSERT INTO @Location VALUES
(1, 'Madrid'), (2, 'AK'), (3, 'AR')
INSERT INTO @States VALUES
('AK'), ('AL'), ('AR')
SELECT l.Id,
s.St... | Do a LEFT JOIN and check for NULLs due to non-matching states:
```
insert into target
select source.id, states.state,
case when states.state is null then location end as Other_Locale
from source left join states
on source.location = states.state
``` | How to place value in column A if it exist in another table, otherwise, place in column B | [
"",
"sql",
"t-sql",
""
] |
I have collected data from an API to build a history. Initially, I saved *all* values every five minutes. Later, I changed my program to only save data that has changed.
Now, I want to clean up my old data and remove all values where the `count` has not changed from the previous record within the same `account` and `i... | You can use the following query:
```
DELETE history
FROM history
INNER JOIN (SELECT MIN(time) AS minTime, account, id, count
FROM history
GROUP BY account, id, count) AS h
ON history.account = h.account AND history.id = h.id AND history.count = h.count
WHERE history.time > h.minTime
```
[**D... | Valuing clarity, this is what I would recommend if one of my reports were trying to do this:
```
select *
from mytable
QUALIFY LAG(count, -1) OVER(PARTITION BY account, id ORDER BY time) != count
```
This returns the table without rows where the count from one row is the same as the count from the last one within the... | Delete only consecutive duplicate rows | [
"",
"mysql",
"sql",
"sql-delete",
""
] |
I have column with dates in format
> year/number\_of\_week\_in\_year/number\_of\_day\_of\_the\_week, for example:
>
> 2015015 = 01.01.2015
How to write query which convert this date to `RRRRmmdd` format? | Here's an untested answer for you, as I don't have access to SQL Server to fiddle around (on my phone at the moment).
The easy part is to get at DATE value for the year...
```
DATEADD(year, (input / 1000) - 1900), 0)
```
Then you need to add a certain number of days to it...
- 7 days for each week (not including w... | Here's a simple solution I threw together, probably not the cleverest way to do it but hopefully makes sense:
```
DECLARE @inDate CHAR(7),
@inYear CHAR(4),
@inWeek INT,
@inDay INT,
@OutDate DATETIME;
SET @inDate = '2015015';
SET @inYear = SUBSTRING(@inDate, 0, 5);
SET @inWeek = CAST(S... | Convert week date to calendar date | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have scoured the documentation for Poco but could not find a way to retrieve the last inserted id for an INSERT INTO Table operation.
The [Statement::execute](http://pocoproject.org/docs/Poco.Data.Statement.html#7389) documentation says that it returns the number of records affected (which could be greater than one ... | For SQLite, execute a statement, SELECT last\_insert\_rowid()
I know that isn't a generic answer.
But, this is how they do it in [Ti.Database](https://github.com/marshall/titanium/blob/master/modules/ti.Database/database_binding.cpp) module - which is a module for Titanium that uses poco. They select last\_insert\_ro... | There is no such facility in Poco. Rather than bending backwards to abstract something that is inconsistent across different back-ends, we chose not to provide it at all and leave users to deal directly with the back-end. See [this discussion](https://sourceforge.net/p/poco/feature-requests/60/). | How do I get the last inserted id in a generic way with Poco? | [
"",
"sql",
"sqlite",
"poco-libraries",
""
] |
I am interested in manipulating my data like so:
My Source Data:
```
From | To | Rate
----------------
EUR | AUD | 1.5895
EUR | BGN | 1.9558
EUR | GBP | 0.7347
EUR | USD | 1.1151
GBP | AUD | 2.1633
GBP | BGN | 2.6618
GBP | EUR | 1.3610
GBP | USD | 1.5176
USD | AUD | 1.4254
USD | BGN | 1.7539
USD | EUR | 0.... | I can suggest something very easy, if it doesn't matter which one of then you want, than you can pick only the one that his rate is bigger than 1 or on the contrary the one smaller. Each pare should be 1 rate bigger and one smaller (make sense) so
```
Select * from table where rate>1
``` | One way to remove the duplicates that doesn't depend on the rates:
```
select s.*
from source s
where from < to
union all
select s.*
from source s
where to > from and
not exists (select 1 from source s2 where s.from = s2.to and s.to = s2.from);
```
Note: I did not put escape characters around `from` and `to`, a... | SQL Distinct Pair Groupings | [
"",
"sql",
""
] |
I have table with hierarchical, parent-child relations and want to order it by that hierarchy. Table is:
```
id|parent|type
--------------
1 |0 |1
2 |0 |1
3 |0 |1
4 |0 |2
5 |0 |2
6 |2 |2
7 |3 |2
```
And as result I want this:
```
id|parent|type
--------------
1 |0 |1
2 |0 |1
6 |2 ... | Using the order by [`hierarchyid`](https://msdn.microsoft.com/en-us/library/bb677290(v=sql.105).aspx) with cte is simple, not test for recursive relations
```
DECLARE @Data table (Id int identity(1,1) primary key, Parent int, Type int)
INSERT @Data VALUES
(0, 1),
(0, 1),
(0, 1),
(0, 2),
(0, 2),
(2, 2),
(3, 2)
SELEC... | Can be done with the following recursive CTE:
```
WITH cte AS (
SELECT *,
CAST(ROW_NUMBER() OVER(ORDER BY id) AS REAL) rn,
1 level
FROM tbl
WHERE parent = 0
UNION ALL
SELECT t2.*,
cte.rn + (CAST(ROW_NUMBER() OVER(ORDER BY t2.id) AS REAL) / POWER(10, cte.level)) rn,
cte.level + 1 level
FROM ... | How to order rows by hierarchy | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Below is picture of two tables, owners and vehicles.
I need to find out the owner who has all types of bikes.
[](https://i.stack.imgur.com/F7rjS.png)
Example:
O\_id 100,O\_id 101,O\_id 102 have bikes with V\_id=1, but
O\_id 103 has all types of bik... | Group by the `o_id`that you want to get.
Take only those groups having the same number (`count(v_id)`) of bikes that exist in total `(select count(*) from vehicles where v_type = 'bike')`
```
select o.o_id
from owner o
join vehicles v on o.v_id = v.v_id
where v.v_type = 'bike'
group by o.o_id
having count(distinct... | ```
with bykes as (
select array_agg(v_id) as byke_ids
from vehicle
where lower(v_type) = 'byke'
), owner as (
select o_id, array_agg(v_id) as v_ids
from owner
group by o_id
)
select o_id
from owner cross join bykes
where v_ids @> byke_ids
;
o_id
------
103
```
The schema:
```
create table ow... | select owner who has all types of bikes | [
"",
"sql",
"database",
"postgresql",
"join",
"subquery",
""
] |
I have a pretty simple sample query that I am trying to complete.
[SQL Fiddle](http://sqlfiddle.com/#!3/da20e/3)
```
SELECT
month(s.report_date),
COALESCE(COUNT(*),0)
FROM
stat_summary s LEFT OUTER JOIN ref_months m on MONTH(s.report_date) = m.month_id
GROUP BY month(s.report_date)
```
My results look li... | You need to use the months table as the primary one:
```
SELECT
m.month_id,
COALESCE(COUNT(s.report_date),0)
FROM ref_months m
LEFT JOIN stat_summary s
ON MONTH(s.report_date) = m.month_id
GROUP BY m.month_id;
``` | You can change `LEFT JOIN` table order, and there is no need for `COALESCE`:
**[SqlFiddleDemo](http://sqlfiddle.com/#!3/da20e/14/0)**
```
SELECT
m.month_id,
[count] = COUNT(s.report_date)
FROM ref_months m
LEFT JOIN stat_summary s
ON MONTH(s.report_date) = m.month_id
GROUP BY m.month_id;
``` | LEFT OUTER JOIN not returning NULL values | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
1. 501--> 588
2. 588--> 588
3. 589--> 688 | I'm going to assume that you want the new number to be 12 less than the next 100 (so: -12, 88, 188, 288, etc).
So you'd first off, add 12 to your number, then divide it by 100. That will provide you with a number with decimals that you can now find the ceiling value for. Then you need to multiply that by 100 and subtr... | TRUNC and ROUND functions can be invoked with negative precision. So I get the hundred part and add 88 or 188 depending if the rest of the number is greater than 88 or not.
```
WITH data(val) AS (
SELECT 88 FROM DUAL UNION ALL
SELECT 89 FROM DUAL UNION ALL
SELECT 501 FROM DUAL UNION ALL
SELECT 588 FROM... | How do roundup in to a specific number in Oracle SQL? | [
"",
"sql",
"oracle",
""
] |
```
Declare @Date date = getdate()
select DATEpart(WEEKDAY,@Date)as day32
SELECT CAST(@Date AS tinyint)
If @Date !=7 and @Date!=1
```
I need help converting a `date` data type to a `tiny int`
This is the error message I get when I try to execute
> Explicit conversion from data type date to int is not allowed. | It should be like this:
```
DECLARE @Date DATE = GETDATE(),
@TinyDate TinyInt
SELECT @TinyDate = CONVERT(TINYINT,DATEPART(WEEKDAY, @Date))
```
DATE can't be converted to INT so you have an error. | Try this with
```
SELECT DATEPART(WEEKDAY,GETDATE())
```
But please be aware of the influence of your system's culture. Some countries start their week on Monday other on Sunday...
You should read a bit about DATEFIRST-option
```
SELECT @@DATEFIRST --Your current setting
``` | SQL - Converting Datepart to tinyint | [
"",
"sql",
"sql-server",
""
] |
I am working on an application, trying to improve performance. Obviously I will be doing my own profiling and testing, but I would like to know if there is a "consensus" or known best practice.
In the old SQL days, one of the main things to do to improve efficiency was to not select data you aren't going to consume. I... | Use table splitting which allows you to split a table into more than one entity without modifying the underlying table. The "less accessed" properties can be lazy loaded on demand or loaded eagerly, behaving as any other navigation property. Note the key here is that the additional entities use their pk as the fk to th... | you can project into named types.
```
var projection = Repository.GetAll()
.AsNoTracking()
.Select(r => new ParentModel()
{
Id = r.Id,
RandomId = r.RandomId,
State = r.State,
RequestType = r.RequestType,
CreatedDate = r.CreatedDate,
... | In Entity Framework is it more efficient / preferred to create projections rather than selecting full entities? | [
"",
"sql",
"asp.net-mvc",
"performance",
"entity-framework",
"rest",
""
] |
I have data in a similar format as this
```
+--------+------------+-------+
| type | variety | price |
+--------+------------+-------+
| apple | gala | 2.79 |
| apple | fuji | 0.24 |
| apple | limbertwig | 2.87 |
| orange | valencia | 3.59 |
| orange | navel | 9.36 |
| pear | bra... | Find fruits with the lowest price:
```
select distinct on (type) type, variety, price
from fruits
order by 1, 3;
type | variety | price
--------+----------+-------
apple | fuji | 0.24
cherry | bing | 2.55
orange | valencia | 3.59
pear | bartlett | 2.14
(4 rows)
```
Find fruits with the highes... | Problems of this nature (get the largest, smallest, average, first, last, ... for each group in a table) are best solved with a so-called [window function](http://www.postgresql.org/docs/current/static/tutorial-window.html). With window functions you `PARTITION` the data into groups (here on column `"type"`) and then a... | How to select the lowest and highest value joined in one row postgres | [
"",
"sql",
"postgresql",
""
] |
So my title might not make sense. Here's what I am trying to do.
```
C1 C2 C3
A1 yes X1
A2 no X1
A3 maybe X1
A4 yes X2
```
So I have a condition where C2 <>'no'. In this case I want the result to only include
```
C1 C2 C3
A4 yes X2
```
... | Use `minus` to get a list of all `c3`s which don't have a `no` for `c2`. and select only those rows from the table.
```
select * from table
where c3 in(
select distinct c3 from table
minus
select distinct from table where c2 = 'no' )
``` | You could try:
```
with x as (
select 'a1' as col1, 'yes' as col2, 'x1' as col3 from dual
union all
select 'a2' as col1, 'no' as col2, 'x1' as col3 from dual
union all
select 'a3' as col1, 'maybe' as col2, 'x1' as col3 from dual
union all
select 'a4' as col1, 'yes' as col2, 'x2' as col3 fro... | Restrict column with multiple values not appear if one condition is also met | [
"",
"sql",
"oracle",
""
] |
I am trying to read multiple values from parameter, store it in a variable and later use it in the select statement to pull multiple values.
```
declare @codes XML = N'<Root>
<List Value="120" />
<List Value="110" />
</Root>';
declare @codeL... | Your problem is here:
```
declare @codeList VARCHAR(MAX) = (SELECT T.Item.value('@Value[1]','VARCHAR(MAX)') FROM @codes.nodes('/Root/List') AS T(Item));
```
Your `select` returns two results (120, 110), but a scalar `VARCHAR` variable can only hold one.
You can fix it by creating a table variable:
```
DECLARE @co... | If you need to store multiple values for use later, use a TABLE VARIABLE to hold the results, like this:
```
DECLARE @dataCodes TABLE (DataCode varchar(MAX));
INSERT INTO @dataCodes
SELECT T.Item.value('@Value[1]', 'varchar(max)')
FROM @codes.nodes('/Root/List') AS T(Item);
```
You can then use the "`WHERE ... | Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, | [
"",
"sql",
"sql-server",
""
] |
My records looks like:
```
aid cmpyname rid imgpath
1 abc 1 ~/img/aa.jpg:~/img/bb.jpg:~/img/cc.jpg:
2 abc 1 ~/img/dd.jpg:~/img/ee.jpg:~/img/ff.jpg:
3 xyz 2 ~/img/gg.jpg:~/img/hh.jpg:~/img/ii.jpg:
4 xyz 2 ~/img/jj.jpg:~/img/kk.jpg:~/img/ll.jpg:
```
What I want to ge... | ```
select distinct rid,imgpath,rid from(
select imgpath=(select imgpath + ', ' AS 'data()'
FROM tbl_Temp
where tbl_Temp.rid=rid FOR XML PATH('') )
,id,cmpyname,rid from tbl_Temp
) as temp
``` | ```
select max(cmpyname) as cmpyname, rid,
stuff((
select imgpath
from Records t1
where t1.rid = t2.rid
order by t1.aid
for xml path(''), type).value('.', 'varchar(max)'), 1, 0, ''
) as imgpath
from Records t2
group by rid;
```
<http://sqlfiddle.com/#!18/46822/1> | Get 3 rows data in 1 row | [
"",
"sql",
".net",
"sql-server-2008",
"c#-4.0",
""
] |
In my MySQL db i have these 3 tables:
```
ACCOUNT (primary key is name)
name
directory
birthdate
sex
FILES (primary key is id)
id (autoincrement)
name (account foreign key)
filename
uploaded_date
CHECKED (primary key is the couple name - filename)
name (account foreign key)
filename (files foreign key)
```... | try this
```
SELECT
a.*, f.filename, f.uploaded_date, IFNULL(c.cnt, 0) as 'checkedCount'
FROM
account a
LEFT OUTER JOIN files f ON a.name = f.name
LEFT OUTER JOIN (SELECT name, COUNT(*) FROM checked GROUP BY 1) c ON a.name=c.name
``` | So I'm guessing you know how `count` works right? By using a count you need a group by clause.
Example:
```
SELECT count(name) as count, name FROM CHECKED GROUP BY name
```
Now here's the problem. You have a big nasty join that you want to do a count on. So lets join the tables, alias them, and then do a count on a ... | Query sql to find row's count from another table | [
"",
"mysql",
"sql",
"join",
""
] |
I have a table like this:
```
+-------------+-----------+------------+
| sample_name | test_name | test_value |
+-------------+-----------+------------+
| s1 | t1 | 1.5 |
| s2 | t2 | 3 |
| s3 | t1 | 8 |
| s4 | t3 | 5 |
+-... | if there are too much values for `test_name` then you may use ***pivot*** within ***dynamic sql***:
```
declare @Names varchar(max)
select @Names = coalesce(@Names + ', ', '') + test_name
from (select distinct test_name from tbl) t
exec('
SELECT *
FROM tbl t
PIVOT (SUM(test_value)
FOR Test_name
IN... | [SQL Fiddle](http://sqlfiddle.com/#!3/9eecb7db59d16c80417c72d1/2294)
**MS SQL Server 2008 Schema Setup**:
**Query 1**:
```
DECLARE @Table TABLE(sample_name VARCHAR(10), test_name VARCHAR(10), test_value DECIMAL(10,2))
INSERT INTO @Table VALUES
('s1','t1',1.5),
('s2','t2',3 ),
('s3','t1',8 ), ... | Transposing a column values into column headers | [
"",
"sql",
"sql-server",
""
] |
Here is what I want to achieve, in pseudocode
```
part1 = select from foo ...
part2 = init empty
foreach row in part1
part2 += select from foo where row.something as condition in here
union part1, part2
```
Is it possible to do it in one query?
This is the structure
```
parent_name | name
------------+-------
nu... | Looks like you're after a hierarchical query:
```
with sample_data as (select null parent_name, 'item1' name from dual union all
select 'item1' parent_name, 'item2' name from dual union all
select 'item1' parent_name, 'item3' name from dual union all
selec... | You can use a hierarchical query:
```
SELECT parent_name, NAME
FROM table1
WHERE LEVEL <= 3
CONNECT BY PRIOR NAME = parent_name
START WITH parent_name IS NULL;
ORDER BY 1 NULLS FIRST;
```
For me it is not clear why you don't want "item6" to be shown, that is not logical for me. Anyway, you achieve it by this:
```
SE... | How to use select result as input for the second select (like foreach)? | [
"",
"sql",
"oracle",
""
] |
Given this mockup:
```
+-----------+-------------+---------------------------+
| item_id | item_name | desc |
+-----------+-------------+---------------------------+
| 1 | Product 1 | lorem ipsum dolor... |
| 2 | Product 2 | lorem mauris eu... |
| 3 | P... | this sort of search requirement sounds a good candidate for [full text search](https://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html).
Full text search is (or at least can be) more of a "search engine" like search as opposed to the traditional sql `like` searches. With full text searching, the order of the word... | I think it is simpler to look for each word separately:
```
SELECT *
FROM items
WHERE (item_name like '%lorem%' and item_name like '%ipsum%') or
(`desc` like '%lorem%' and `desc` like '%ipsum%');
```
This generalizes most easily to more words and to more columns.
If you like, you can concatenate the values tog... | SQL search for words in any order | [
"",
"mysql",
"sql",
""
] |
I need to compute the factorial of a variable in Google BigQuery - is there a function for this? I cannot find one in the documentation here:
<https://cloud.google.com/bigquery/query-reference#arithmeticoperators>
My proposed solution at this point is to compute the factorial for numbers 1 through 100 and upload that... | Extending Mikhail's answer to be general and correct for computing the factorial for all number 1 to n, where n < 500, the following solution holds and can be computed efficiently:
```
select number, factorial
FROM js(
// input table
(
SELECT
ROW_NUMBER() OVER() AS number,
some_thing_from_the_table
FROM
... | Try below. Quick & dirty example
```
select number, factorial
FROM js(
// input table
(select number from
(select 4 as number),
(select 6 as number),
(select 12 as number)
),
// input columns
number,
// output schema
"[{name: 'number', type: 'integer'},
{name: 'factorial', type: 'integer'}]",
// function
"function(r,... | Factorial in Google BigQuery | [
"",
"sql",
"google-bigquery",
"factorial",
""
] |
Is this possible in one SQL statement?
I pointer to a nice SQL tutorial on the subject is also appreciated.
I know I can use a command like `SELECT * FROM MYTAB WHERE MYFIELD = 0`
and then use a server script to go through the result and `UPDATE MYFIELD`
of the result rows. | Wouldn't this work?
`UPDATE MYTAB SET MYFIELD=1 WHERE MYFIELD=0`
**Edited to Add:**
If you are interested in SQL tutorials, a lightweight one that has the nice feature of allowing you edit and run SQL commands in the webpage to see how they work is from w3schools here: <http://www.w3schools.com/sql/> | If you can execute a query to read the data you should also be able to write the data;
`UPDATE MYTAB SET MYFIELD = 99 WHERE MYFIELD = 0`
* [UPDATE (Transact-SQL)](https://msdn.microsoft.com/en-us/library/ms177523.aspx)
* [UPDATE Statement (Oracle)](http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/update_statemen... | sql: how to select all records with field set to 0 and set the value of that field to one | [
"",
"sql",
""
] |
There is this query that I keep using over and over:
```
SELECT column_name, count(column_name) FROM table_name GROUP by column_name ORDER BY COUNT(column_name) DESC
```
I use this to check which different values there are in a column and how often they occur.
Because I use this query so often and it's repeating the ... | There is no way to do it directly. You need to use dynamicSQL approach. Assuming you pass correct table and column names. Below one should work.
```
CREATE PROCEDURE countcv @table_name VARCHAR(50),@column_name VARCHAR(50)
AS
BEGIN
declare @SQL nvarchar(max)
set @SQL = 'SELECT '+@column_name+',COUNT('+@column_name+... | I believe that @Julien Vavasseur and @Dark Knight has already addressed to your question.
However, I would like to add here that, Sql Server 2008 introduced [Table-Valued Parameter](https://msdn.microsoft.com/en-us/library/bb675163(v=vs.110).aspx) by using which we can pass table type variable to the stored procedures.... | How to use table as variable in stored procedure | [
"",
"sql",
"sql-server",
""
] |
Lets say I have a table with 2 columns (**a**, **b**) with following values:
```
a b
--- ---
1 5
1 NULL
2 NULL
2 NULL
3 NULL
```
My desired output:
```
a
---
2
3
```
I want to select only those distinct values from column **a** for which every single occurrence of this value has NULL... | If I understand correctly, you can do this with `group by` and `having`:
```
select a
from t
group by a
having count(b) = 0;
```
When you use `count()` with a column name, it counts the number of non-NULL values. Hence, if all values are `NULL`, then the value will be zero. | It's fairly simple to do:
```
SELECT A
FROM table1
GROUP BY A
HAVING COUNT(B) = 0
```
Grouping by A results in all the rows where the value of A is identical to be transferred into a single row in the output. Adding the `HAVING` clause enables to filter those grouped rows with an aggregate function. `COUNT` doesn't c... | SQL - Select from column A based on values in column B | [
"",
"sql",
"t-sql",
""
] |
The following query attempts to do what can be expressed as `@users.courses` (where @user.id = 1). I'm giving this information as I'm not exactly sure if this is right since the query doesn't run
```
SELECT * FROM courses WHERE courses.id =
courses_users.user_id AND courses_users.user_id = 1
```
SQL complains:
> #... | Your `where` clause references `courses_users`, but this tables never appears in a `where` or `join` clause.
You should either added it to the `from` clause:
```
SELECT *
FROM courses, courses_users -- Here!
WHERE courses.id = courses_users.user_id AND
courses_users.user_id = 1
```
Or, better yet, use an... | You're missing a `JOIN`. The statement doesn't know about `courses_users` unless you `JOIN` to it. For this your query needs to look something like this:
```
SELECT *
FROM courses
JOIN courses_users ON
courses.id = courses_users.user_id
WHERE
courses_users.user_id = 1
``` | SQL complaining about an existing field | [
"",
"mysql",
"sql",
"ruby-on-rails",
""
] |
I know i can use a subquery to make an insert after selecting rows from the database.
```
INSERT INTO wp_43_term_relationships (object_id, term_taxonomy_id, term_order)
SELECT ID, 8363, 0 FROM
( SELECT DISTINCT
wp_43_posts.ID
FROM
wp_43_posts
INNER JOIN wp_43_term_relationships ON wp_43_term_relationships.object_id = ... | If you replace the constant with the second query in ()'s, it should work.
Like this:
```
INSERT INTO wp_43_term_relationships (object_id, term_taxonomy_id,term_order)
SELECT ID,
(SELECT wp_43_term_taxonomy.term_taxonomy_id FROM wp_43_term_taxonomy WHERE wp_43_term_taxonomy.term_id = 8363),
0 FROM
... remaining of the... | just bring it into the subquery and use an extra join:
```
INSERT INTO wp_43_term_relationships (object_id, term_taxonomy_id, term_order)
SELECT ID, someval, 0 FROM
( SELECT DISTINCT
wp_43_posts.ID,t.term_taxonomy_id someval
FROM
wp_43_posts
INNER JOIN wp_43_term_relationships ON wp_43_term_relationships.object_id = w... | MYSQL: create an insert with data from two subqueries | [
"",
"mysql",
"sql",
""
] |
So, I`ve got two columns t1.NAME and t2.ITEMS, for each neme there can be more than one item assigned to it, so I want to select it like:
```
| NAME | ITEMS |
JOHN 1
2
BEN 4
7
3
DAVE 5
```
P.s. if it helps, they are connected by t1.id = t2.names\_id | Result of my below query is very close to what you want.. the only difference is, there is no blank name, because you cannot directly do that result in one step query.. each item belong to name of each id in t1. BUT you can do some trick there if you want to get the exact result, you can use `UPDATE` to do some trick w... | This kind of operation should be done in presentation layer.
[](https://i.stack.imgur.com/BDPYq.png)
[](https://i.stack.imgur.com/uF3y0.png)
But if you insist you can use sth like:
... | Get rid from one column duplicate values in two column select | [
"",
"sql",
"oracle",
"output-formatting",
""
] |
I'm writing an application that calculates the ranking of teams in the pool stages of a rugby competition *(Rugby World Cup 2015, but it could apply to many other pool-based competitions)*.
At the completion of the pool phase, points are calculated based on wins/draws/losses/bonus points, and teams are ranked by point... | This need sql 2012+ using `LEAD()` and `LAG()` [**functions**](http://blog.sqlauthority.com/2013/09/22/sql-server-how-to-access-the-previous-row-and-next-row-value-in-select-statement/), Also require only two team have same Rank at this moment.
**SCHEMA**
```
CREATE TABLE Table1
([team] varchar(1), [rank] int);
... | This is complicated, but I would try the following.
1. Make a view each combination of opponents and who wins the tie.
2. With the results of your current ranking add in a column for the prior player, a column for prior rank, a column for next rank using windowing functions
3. Join to the view in step 1
4. Make a case... | Ranking teams equal on points in a pool based on who won the game they played | [
"",
"sql",
"sql-server",
"algorithm",
"t-sql",
""
] |
I seem to have some kind of lapsus...
How can I format a continuous credit card number to have blank space after every 4 digits in T-SQL?
```
TableName | Cards |
ColumnName | CardNumber |
ExampleInput | 80756201005803400471 | varchar(20)
ExampleOutput | 8075 6201 0058 034... | Something like this:
```
select stuff(stuff(stuff(stuff(ccn, 17, 0, ' '), 13, 0, ' '), 9, 0, ' '), 5, 0, ' ')
```
That is, nested called to `stuff()`. Note: you need to start at the end of the string or else be very careful about the offsets. | Something like this if the length is fixed:
```
Select *
, SUBSTRING(n, 1, 4) + ' '
+ SUBSTRING(n, 5, 4) + ' '
+ SUBSTRING(n, 9, 4) + ' '
+ SUBSTRING(n, 13, 4) + ' '
+ SUBSTRING(n, 17, 4) + ' '
From (values('80756201005803400471')) as car(n)
``` | How to insert Spaces in long Credit Card Number every X characters in T-SQL? | [
"",
"sql",
"sql-server",
"t-sql",
"credit-card",
""
] |
I have the following relations.
```
Suppliers( sid: integer, sname: string, address: string)
Parts(pid: integer, pname: string, color: string)
Catalog( sid: integer, pid: integer, cost: real)
```
The problem asks me to find the pnames of parts supplied by Acme Widget Suppliers and no one else. I wrote the following S... | This can work:
```
select p.pname from Catalog c
join Parts p on p.pid = c.pid
join Suppliers s on s.sid = c.sid
where s.sname = 'Acme Widget Suppliers'
and p.pid in (select pid as SupplierCount from Catalog c
group by pid having count(*) = 1)
```
The inner `select` is meant to find exclusive parts from... | You are correct. The query you want to make can be greatly simplified. Try the following.
```
SELECT P.pname FROM Parts P, Suppliers S, Catalog C
WHERE C.pid = P.pid
AND C.sid = S.sid
AND S.sname == "Acme Widget Suppliers"
``` | What is a better way to write this SQL query? | [
"",
"mysql",
"sql",
"database",
""
] |
I'm trying to view software that has been installed within the last 30 days. The format of my date is `20150327`. When I try to the following condition in the `where` clause
```
and DateDiff(day,arp.InstallDate0,GetDate()) < 30
```
I receive the following error message:
> Conversion failed when converting date and/o... | You do not need a conversion format for YYYYMMDD when converting to `date`, `datetime2`, and `datetimeoffset`. SQL Server recognizes this ISO standard format with no conversion in these cases, regardless of internationalization settings (there is one setting that affects my preferred format of YYYY-MM-DD; the documenta... | You must use the syntax below, as the first argument for the [`CONVERT` function](https://msdn.microsoft.com/en-us/library/ms187928.aspx) is the target data type
```
CONVERT(datetime,'20150327',112)
``` | Can't convert YYYYMMDD to date | [
"",
"sql",
"sql-server-2008",
""
] |
I want get only year, and only numeric month from date, I try this for month by i get char month, how can i get numeric month, and year ?
```
select to_char(dateper,'MON')
from calcul
group by dateper
``` | You can get a numeric representation in a string by using:
```
select extract(year from dateper) as yyyy, extract(month from dateper) as mm
from calcul
group by yyyy, mm;
```
Or:
```
select to_char(dateper, 'YYYY-MM')
from calcul
group by to_char(dateper, 'YYYY-MM') ;
``` | Month:
```
SELECT date_part('month', now())::integer;
```
Year:
```
SELECT date_part('year', now())::integer;
``` | get only month and year from date | [
"",
"sql",
"postgresql",
""
] |
According to this [Oracle documentation](http://www.oracle.com/technetwork/articles/sql/11g-sqlplanmanagement-101938.html), I can assume that the Optimizer postpones the hard parse and it doesn't generate an execution plan until the first time a prepared statement is executed:
"The answer is a phenomenon called bind p... | The first bind peek actually happens at the first execution. The plan optimization is deferred it doesn't happen at the prepare phase. And later on another bind peek might happen. Typically for VARCHAR2 when you bind two radically different values (i. e. in length of first value 1 byte and later 10 bytes) the optimizer... | This discussion misses a very important point about bind variables, parsing and bind peeking; and this is Histograms! Bind variables only becomes an issue when the column in question have histograms. Without histograms there is no need to peek at the value. Oracle have no information then about the distribution of the ... | Does Oracle chose a default execution plan when parsing a prepared statement? | [
"",
"sql",
"database",
"oracle",
"optimization",
"sql-execution-plan",
""
] |
I'm using SQLite and I"m really green. Essentially I have a table (example below)
```
ID Date QuestNum Value
1 1/1/1990 1 0
1 1/1/1990 2 3
1 1/1/1990 3 2
1 1/2/1990 1 5
1 1/2/1990 2 2
1 1/2/1990 3 6
2 1/1/1990 1 6
2 1/1/1990 2 3
2 1/1/1990 3 6
2 1... | Essentially, you need to **transpose** your rows to columns or **reshape** from long to wide format. In SQL, this can be done with a derived table (type of subquery):
```
SELECT
[ID],
[Date],
Max(CASE WHEN QuestNum = "1" THEN [Value] END) As Q1,
Max(CASE WHEN QuestNum = "2" THEN [Value] END) A... | Use `GROUP BY ID, Date` as group expression.
And SELECT never alters your data, except some functions in some databases (like nextval which modifies a sequence), but these changes are explicitly documented. simple aggregate functions like this are totally safe.
But what you see is not a table, it's only a result. If ... | Multiple row data transformed into single | [
"",
"sql",
"sqlite",
""
] |
I have this sample data and part of the query [See the Fiddle](http://sqlfiddle.com/#!6/b53e9/2). It shows the segment start time and end time. The task is get the sum of all the time segments between 6am to 10pm in seconds. I have filter it on the day but how can I restrict between 6am and 10 pm is difficult for me (M... | ```
WITH splittedDates AS
(
SELECT
userid,
CAST(StartTime as date) 'StartDate',
CAST(EndTime as date) 'EndDate',
CAST(StartTime as time) 'stime',
CAST(EndTime as time) 'etime',
StartTime,
EndTime
FROM Test
), correctedTimes AS (
SELECT userid,
CAS... | I don't have MS SQL in front of me so I can't test this, but how about something like the following?
```
Select
userid,
CASE
WHEN DateDiff(day, starttime, endtime) = 0 and starttime>=6am and endTime<=10am
THEN datediff(second, starttime, endtime)
END As TotalSecondsFromSixAMToTenPM
FROM
Test
`... | How can I select records on the basis of their timings between specific times in SQL server | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have the following three Tables that I am having trouble joining because there is not a unique key in between all three
Computers, Clients & Drives
```
*Table Computers*
ComputerID ClientID Name Domain UserName OS
========================================================================
1 ... | It all seems to work for me:
<http://sqlfiddle.com/#!6/f5d89/1>
It is in sql2014, but I don't think SQL flavours will be getting in the way here.
Which rows do you see missing? | Your code looks solid. The only thing I could think that may be an issue is the order of your JOINS.
There is a good article about Join order here.
<https://social.msdn.microsoft.com/Forums/sqlserver/en-US/9d223e3f-c040-4eb9-a44e-5556e85a821b/inner-join-after-left-outer-join> | Joining 3 x MYSQL Tables together with 2 Different Unique Keys | [
"",
"mysql",
"sql",
""
] |
Is there a way to pull back all records that have overlapping datetimes based on a user?
For instance;
TableA has the following rows;
```
TrainerID StartTime EndTime
1234 10-1-2015 08:30 10-1-2015 09:00
1234 10-1-2015 08:45 10-1-2015 09:15
1234 ... | The EXIST code below should give you that answer. The code ensures that the start time of the clashing entry is before the start of the main list entry while the start time of the clash is still after the start time of the mail list entry.
```
SELECT *
FROM tblTest clashing
WHERE EXISTS
(
SELECT 1
FROM tblTe... | Firstly you should sort by trainerId and Start\_time. And then join two tables with correct condition.
Try this query:
```
;WITH TrainersTemp AS
(
SELECT *, ROW_NUMBER() OVER ( ORDER BY trainerid, Start_Time) AS row_num
FROM Trainers
)
select t2.* from TrainersTemp t1
join TrainersTemp t2 on t1.TrainerId... | Find all rows where start date is before a prior end date | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2012",
""
] |
For example, I have the following relations.
```
Suppliers( sid: integer, sname: string, address: string)
Parts(pid: integer, pname: string, color: string)
Catalog( sid: integer, pid: integer, cost: real)
```
I write the following MYSQL query to find the sids of suppliers who supply only red parts.
Example 1)
```
S... | There are no difference between your two queries. They are exactly the same. The only difference is that you are using different alias for the table `Catalog`on then. The parser will resolve the alias from most inside to outside so in your query example 1
```
SELECT DISTINCT C.sid FROM Catalog C
WHERE C.sid NOT IN(
... | Your queries will both work. Should you want to do it without a subquery try this:
```
select c.sid
from Catalog c inner join Parts p on p.pid = c.sid
group by c.sid
having min(p.color) = 'red' and max(p.color) = 'red'
```
or
```
having count(case when p.color = 'red' then 1 else null end) = count(*)
```
And here's... | If I want to query the same table twice in not in clause, can I use the same table alias? | [
"",
"mysql",
"sql",
"database",
""
] |
I'd like to do a `prorata` calculation in PL/SQL but I have no clue how to do so.
Here my exemple :
```
ID class Wages Premium
1 A 15000 250
2 A 10000 0
```
I'd like to compute premium on a prorata basis within class, i.e. for every ID in each CLASS, I'd like to compute the premium on a pro... | The most efficient method would be to use ratio\_to\_report(), which is often strangely ignored.
```
select id,
premium,
sum(premium) over (partition by class) *
ratio_to_report(wages) over (partition by class) prorated_premium
from my_table
```
For an update I would look at:
```
update (que... | You can easily calculate the new premium values with analytic functions:
```
create table prorata_test as
select 1 id,
'A' class,
15000 wages,
250 premium
from dual
union all
select 2 id,
'A' class,
10000 wages,
0 premium
from dual
union all
select 3 id,
'B' class,
... | How to compute prorata calculation in PL/SQL? | [
"",
"sql",
"oracle",
"plsql",
""
] |
Reading this [article](http://www.dalibo.org/_media/understanding_explain.pdf) about the `EXPLAIN` command I come across the so called `invisible rows` concept. To me more specific:
> In a sequential scan, the executor needs:
>
> * to read all the blocks of relation foo
> * to check every row in each block to filter “... | It's basically a consequence of MVCC and transactions. If you start a transaction then rows created by a different session will normally not be visible to your session until the transaction has run its course. This is to prevent the state of a transaction becoming inconsistent during its execution.
There are exception... | Invisible rows are rows that are not visible to a transaction (lets call it `T1`) when started.
A typical scenario is the following:
A transaction `T2` starts its execution. `T2` consists in the query
```
UPDATE users SET name = 'John' WHERE age < 18
```
Meanwhile, the transaction `T1` (concurrently with `T2`) star... | What are invisible rows in postgresql? | [
"",
"sql",
"postgresql",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.