Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
My database Table looks like:
```
ID | INDEX | Value |
1 | 0 | 3 |
1 | 1 | 5 |
1 | 2 | 7 |
2 | 0 | 4 |
2 | 1 | 6 |
2 | 2 | 2 |
```
What I want my output to look like is the difference of the values column based on their index
i.e. value(id=2,index = i) - value(id ... | You can do this by join
```
select
t1.ind, t1.value - t2.value as delta
from My_Table as t1
inner join My_Table as t2 on t2.id = 2 and t2.ind = t1.ind
where t1.id = 1
```
Or by simple aggregate:
```
select
ind, sum(case id when 1 then 1 when 2 then -1 end * value) as delta
from My_Table
group by ind
``` | Do you want something like this?
```
select
col1.value column1,
col2.value column2,
col2.value - col1.value AS delta
From My_Table col1
INNER JOIN My_Table col2
ON col1.index = col2.index
AND col2.id = 2
where col1.id = 1
``` | T-sql using values from one table and displaying them in different columns | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm almost certain you cannot do this within the context of the case statement, and I haven't been able to find any documentation about it, but is it possible to do the following:
```
SELECT CASE WHEN testValue > 2
THEN testValue(Without Repeating it) ELSE FailValue)
END
FROM Table
```
A better more thorough exampl... | Like so
```
DECLARE @t INT=1
SELECT CASE
WHEN @t>0 THEN
CASE
WHEN @t=1 THEN 'one'
ELSE 'not one'
END
ELSE 'less than one'
END
```
EDIT:
After looking more at the question, I think the best option is to create a fu... | The query can be written slightly simpler, like this:
```
DECLARE @T INT = 2
SELECT CASE
WHEN @T < 1 THEN 'less than one'
WHEN @T = 1 THEN 'one'
ELSE 'greater than one'
END T
``` | SQL Server - Case Statement | [
"",
"sql",
"sql-server",
"syntax",
"case",
""
] |
I have the following example.
```
DECLARE @String varchar(100) = 'GAME_20131011_Set - SET_20131012_Game'
SELECT SUBSTRING(@String,0,CHARINDEX('_',@String))
SELECT SUBSTRING(@String,CHARINDEX('- ',@STRING),CHARINDEX('_',@STRING))
```
I want to get the words 'GAME' and 'SET' (the first word before the first '\_' from ... | As long as your two parts will always be separated be a specific character (`-` in your example), you could try splitting on that value:
```
DECLARE @String varchar(100) = 'GAME_20131011_Set - SET_20131012_Game'
DECLARE @Left varchar(100),
@Right varchar(100)
-- split into two strings based on a delimeter
S... | Try this
```
SELECT SUBSTRING(@String,0,CHARINDEX('_',@String))
SELECT SUBSTRING(@String,CHARINDEX('- ',@STRING)+1, CHARINDEX('_',@STRING)-1)
``` | T-SQL SUBSTRING at certain places | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2012",
""
] |
Can you please help me converting the following Oracle `MERGE` statement into a valid `UPSERT` statement for use in a PostgreSQL 9.3 database?
```
MERGE INTO my_table a
USING (SELECT v_c1 key,
v_c2 AS pkey,
v_c3 AS wcount,
v_c4 AS dcount
FROM ... | I don't think there's UPSERT statement in PostgreSQL 9.3, but you can do this:
```
with cte_dual as (
select
v_c1 as key,
v_c2 as pkey,
v_c3 as wcount,
v_c4 as dcount
), cte_update as (
update my_table as a set
wcount = b.wcount,
dcount = b.dcount
from cte_du... | I ran on this today, read these, the docs, eventually used something very similar to what to my understanding the docs are advising now for `UPSERT`:
```
INSERT INTO table (
$INSERT_COLUMN_NAMES
)
VALUES (
$INSERT_COLUMN_VALUES
)
ON CONFLICT (
$LIST_OF_PRIMARY_KEY_COLUMN_NAMES
)
DO UPDATE SET
$UPDATE_S... | Migrating an Oracle MERGE statement to a PostgreSQL UPSERT statement | [
"",
"sql",
"oracle",
"postgresql",
"upsert",
"sql-merge",
""
] |
I tried to understand how ON and WHERE would affect the execution of the statement but no luck..
I have this statement which gives me the expected result:
```
SELECT DISTINCT u1.email
FROM user u1
LEFT JOIN user u2
ON u1.email = u2.email
WHERE u1.id != u2.id
```
[Correct output](http://sqlf... | This happens because in the first case the `where` clause is applied *after* the join and will remove all rows that were only included by the "outer" join. Those rows are removed because the `email` column from the `u2` table will be null for those and any comparison with `null` yields undefined which means that the `w... | For starters, your sqlfiddle isn't matching your code on this page. Minor issue though.
Short answer is this: when you add a where clause that checks criteria on the left join, it essentially makes it act like an inner join. | LEFT JOIN Statement with ON and WHERE | [
"",
"sql",
""
] |
let me start off by saying Yes this is a homework question.
It seems so simple but I can't get it to work. I am just starting sub-queries and I'm guessing that's what my teacher wants here.
here's the question
```
5. Write a SELECT statement that returns the name and discount percent
of each product that has a... | Try this, it's quite similar to yours, but with `not in` you assure that the discount is not present in another product.
```
SELECT p1.ProductName, p1.DiscountPercent
FROM Products AS p1
WHERE p1.DiscountPercent NOT IN
(SELECT p2.DiscountPercent
FROM Products AS p2
WHERE p1.ProductName <> p2.ProductName)... | When checking for uniqueness using `COUNT()` makes it simple, you can either use it in a `HAVING` clause or select it outright.
```
SELECT a.ProductName, a.DiscountPercent
FROM Products a
JOIN (SELECT DiscountPercent, COUNT(DiscountPercent) AS CT
FROM Products
GROUP BY DiscountPercent
)b
ON a.Discoun... | SQL Listing only unique values with subquery | [
"",
"mysql",
"sql",
""
] |
I know my title is a bit misleading but i am unsure of what would be a good title.
Authored has 2 columns namely ID, PubID
Is there anyway i could output the P into my result.
I would like to know for each respective ID, PubID pair, how many rows would have the same PubID but different ID.
```
select a.authorId, P ... | Updated using `count() over()`:
**[Fiddle demo](http://sqlfiddle.com/#!3/156b3/8)**:
```
select a.AuthorId, count(*) over(partition by pubId) counts
from Authored a
order by a.AuthorId;
``` | Please try below query for MS Sql server:
```
select
*,
COUNT(*) over (partition by pubId)
From Authored
where authorId<>pubId
``` | Taking variables outside of query in sql | [
"",
"sql",
""
] |
I have a query to fetch a set of quizzes that are running that day. I want to make sure that the user hasn't already finished that quiz. The query I have is:
```
SELECT qi.qiId, qi.qiTitle, qi.qiDescription, qi.qiDate, qi.qiLeague, qi.qiType, qi.qiNumQuestions
FROM quizzes qi
LEFT JOIN quizOneDaySpecials qo
ON qo.q... | Nulls evaluate to unknown and therefore won't match any operators other than IS NULL or IS NOT NULL. You could either add an OR statement to your qoIsCompleted or you can use IFNULL() function to check if it is null and if it is default the value to something like 0 so that it doesn't match.
```
AND IFNULL(qo.qoIsComp... | You can't compare NULL values and non-null values directly. Under default settings SQL Server doesn't know whether NULL is or isn't equal to 1. It knows only that it's NULL. It looks like what you want is something like
```
WHERE IFNULL(qo.qoIsCompleted, 0) != 1 AND ...
``` | MySQL query returning no results when querying joined table | [
"",
"mysql",
"sql",
"select",
"left-join",
""
] |
I am trying to generate some user analytics in a stored procedure.
Here is the sql code:
```
SELECT count(*),SUM(n.credit) from notifications n
left join questions q on q.id = n.question_id
where n.user_id = u_id and q.question_level = 1 ;
```
The column `q.question_level` has three possible value => `1,2 and 3` I... | Do you mean like this?
```
SELECT
count(*),
SUM(n.credit) AS totalCredit,
SUM(CASE WHEN q.question_level = 1 THEN n.credit ELSE 0 END) as level1_sum,
SUM(CASE WHEN q.question_level = 2 THEN n.credit ELSE 0 END) as level2_sum,
SUM(CASE WHEN q.question_level = 3 THEN n.credit ELSE 0 END) as level3_sum,
SUM... | Try this:
```
SELECT COUNT(*), SUM(n.credit)
FROM notifications n LEFT JOIN questions q ON q.id = n.question_id
WHERE n.user_id = u_id
GROUP BY q.question_level;
``` | Get count and sum on multiple conditions in a single sql statement | [
"",
"mysql",
"sql",
"stored-procedures",
""
] |
Let's say I want to update table `course_main`. My initial query was:
```
update course_main
set data_src_pk1 = 2
where course_id LIKE '%FA2013' and available_ind = 'N'
```
Well this will get some courses(only a small set, fortunately)that I do not want to update. So I have a select statement to retrieve the actual d... | ```
update course_main
set data_src_pk1 = 2
where course_id in (select course_id from course_main
where course_id like '%FA2013' and available_ind = 'N'
and course_id <> 'ENGL-0330-112WE-FA2013'
and course_id <> 'ENGL-0360-112WE-FA2013'
and course_id <> 'ENGL-0390-112WE-FA2013'
and course_id <> 'ARTC-1053-128HY-CEQ113... | How about
```
UPDATE course_main
SET data_src_pk1 = 2
WHERE course_id LIKE '%FA2013'
AND available_ind = 'N'
AND course_id NOT IN ('ENGL-0330-112WE-FA2013','ENGL-0360-112WE-FA2013',.....)
ORDER BY course_id ASC;
```
? | How can I update a table based on results from a select query? | [
"",
"mysql",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have two entities, "User" and "Product", and two tables: One to store which users **viewed** which products and the other to store which users **liked** which products. I want query once and return the results as illustrated below:
Table "Views":

Table "Likes":
... | You can try this out:
```
SELECT user_id, product_id, max(`view`) `view`, max(`like`) `like` FROM (
SELECT user_id, product_id, TRUE `view`, FALSE `like` FROM views
UNION ALL
SELECT user_id, product_id, FALSE, TRUE FROM likes
) s
GROUP BY user_id, product_id
```
Btw, you should try to avoid `view` and `like` as... | ```
SELECT
v.User_ID, v.Product_ID, true AS `View`, IF (l.User_ID, true, false) AS `Like`
FROM views v
LEFT JOIN likes l ON (l.User_ID = v.User_ID AND l.Product_ID = v.Product_ID)
UNION
SELECT
l.User_ID, l.Product_ID, IF (v.User_ID, true, false) AS `View`, true AS `Like`
FROM likes l
LEFT JOIN views v ON (l... | MySQL query to return OR-inclusive relationships from multiple tables | [
"",
"mysql",
"sql",
"join",
""
] |
I have stored procedure like this:
```
alter procedure [dbo].[testdate]
as
begin
declare @current nvarchar(100),
@date1 datetime
select @current = getdate()
select @date1 = getdate()
end
```
While executing I want to show the values of `@current` and `@date1`..
How can I dec... | ```
BEGIN
DECLARE @curent nvarchar(100),
@date1 datetime
SELECT @curent=getdate()
SELECT @date1=getdate()
SELECT @curent
SELECT @date1
END
``` | try
```
alter procedure [dbo].[testdate] as
begin
declare
@curent nvarchar(100),
@date1 datetime
select @curent=getdate()
select @date1=getdate()
select @curent as "CurrentDate"
select @date1 as "Date1"
end
``` | Show the declared variable value while executing stored procedure | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
Using `SQL Server 2012`. I want to select a distinct value from a table `T` if only **one** distinct value exists. Below I have a simplified example of what I'm trying to do.
This data would result in 1 returned value: 'bbb'
```
ID Data
----------
1 'bbb'
```
The same goes for this data:
```
ID Data
------... | ```
SELECT MIN(ID), [Data]
FROM [tablename]
GROUP BY [Data]
HAVING
1=(SELECT COUNT(DISTINCT [Data]) FROM [tablename])
```
or if you don't want to repeat [tablename], you could use something like this:
```
SELECT MIN(ID), MIN([Data])
FROM [tablename]
HAVING MIN([Data])=MAX([Data])
```
Please see fiddle [here](http:... | Where clause logically execute before select statement. So the alias which mentioned in select list is not found in where clause because select would execute next.
true is this :
```
with s as (
SELECT [Data] FROM
(SELECT [Data], COUNT(*) OVER() AS [DinstinctValueCount] FROM
(SELECT DISTINCT [... | Select distinct value if only ONE distinct value exists? | [
"",
"sql",
"sql-server",
""
] |
I created indexes in postgres for the below mentioned table using md5. The indexes and the table are given below:
```
create table my_table(col1 character varying, col2 character varying, col3 character varying);
```
my\_table looks like (I have just given an example. My actual table is of 1Tera Byte):
```
col1 ... | Since you are getting an error when you try to create a standard btree index I am guessing that the data in one or more of these columns is quite large.
The index you created is perhaps best described as "a b-tree index of the md5 hashes of the three columns", rather than an "md5 index of three columns".
In order for... | Create index for each column, not combined column. If you create index for several separated column, postgresql query planar can combine those using what it calls a bitmap index scan. Combining single column indexes is often as fast, and you can use them in any query that references a column that you indexed. Creating ... | Slow performance of postgres even on creating indexes | [
"",
"sql",
"postgresql",
""
] |
I have an sqlite table of card controlled entry door usages.
I need the sum of the even-odd time intervals, so for example the expected sum for card 02 is (12:03 - 08:07) + (16:03 - 14:52) = 03:56 + 01:21 = 05:07
People can move freely in daytime, so there could be many entries for a card.
[Test table](http://cdn.vi... | Query is not hard but time interval handling is!
```
SELECT card_id,
TIME(1721059.5+SUM(JULIANDAY(time)*((SELECT COUNT() FROM t AS _ WHERE card_id=t.card_id AND time<t.time)%2*2-1)))
FROM t
GROUP BY card_id;
```
How it works:
`((SELECT COUNT() FROM t AS _ WHERE card_id=t.card_id AND time<t.time)%2*2-1)` counts a... | I don't have an SQLite available to try this, but something like this ought to work:
```
CREATE TEMP TABLE card_times AS
SELECT time FROM entries
WHERE card_id = 2;
SELECT SUM(strftime("%s", '2000-01-01 ' || x.time || ':00')
- strftime("%s", '2000-01-01 ' || y.time || ':00'))
FROM card_times AS x INNER JOI... | Get sum of paired time differences | [
"",
"sql",
"sqlite",
""
] |
I'm trying an SQLi attack.
The compiler executes the following query despite warnings:
```
select * from users where username='A' or 'B' and password='C';
```
Because the query executes, the attack is successful. Why does this query works and what is it doing? Can I assume that the value 'B' is taken as 'True' in th... | **UPDATE**
Based on your updated question and comments, it would appear that you are aware of the error in your syntax and want to know *specifically* how *MySQL* handles this query.
It would appear the MySQL first converts the character string to an integer value (producing a warning).
MySQL treats any [non-zero nu... | If 'B' is not a boolean then you would need to specify what you are comparing against, which in this case is probably `username`.
Something like;
```
select * from users where username='A' or username='B' and password='C'
```
This would evaluate `username='B' AND password='C'` and then `OR username='A'`
You can als... | And Or conditions in SQL, but not properly nest them | [
"",
"mysql",
"sql",
"logical-operators",
""
] |
First I run all these in java with jdbc driver...
Here I define a table:
```
create table HistoryCCP(
ID NUMBER(6) NOT NULL,
SCRIPT VARCHAR2(1000) NOT NULL
)
```
Here I define a sequence:
```
CREATE SEQUENCE SYSTEM.HistoryId
MINVALUE 1
MAXVALUE 1000000
INCREMENT BY 1
START WITH 1
... | Never rely on sequences for gap free numbering.
The cache value is the number of sequence values that are held in memory by the database server to avoid the need to keep updating it's internal $SEQ table with the most recently used value. If you reduce the cache value then you increase the rate at which the $SEQ table... | NOCACHE would work, but also would be a bad idea under for many reasons, and a total nonsense if you plan to bring your application on a Oracle RAC.
Oracle Sequences are for (internal) unique ID, not for strictly progressive number imposed by requirements. As example, let's say that using a sequence for generating the... | How to increment sequence only by 1? | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
I have a number of tables with values I need to sum up. They are not linked either, but the order is the same across all the tables.
Basically, I would like to take this two tables:
```
CASH TABLE
London 540
France 240
Belgium 340
CHEQUE TABLE
London 780
France 490
Belgium 230
```
To get an output like this t... | ```
select region,sum(number) total
from
(
select region,number
from cash_table
union all
select region,number
from cheque_table
) t
group by region
``` | ```
SELECT (SELECT COALESCE(SUM(London), 0) FROM CASH) + (SELECT COALESCE(SUM(London), 0) FROM CHEQUE) as result
```
'And so on and so forth.
"The COALESCE function basically says "return the first parameter, unless it's null in which case return the second parameter" - It's quite handy in these scenarios." [Source](... | SQL: How to to SUM two values from different tables | [
"",
"sql",
"database",
""
] |
I have a select statement using count and since I am counting the rows instead of returning them how do I make sure that I do not get a duplicate value on a column?
For Example
```
_table_
fName someField
Eric data
Kyle mdata
Eric emdata
Andrew todata
```
I want the count to be 3 because Er... | ```
SELECT Count(DISTINCT fName) From _table_ INTO :var
```
It will count number of distinct elements from `fName` column. | This will do the Job `Select Count(distinct fnmae) From _table_ INTO :var` | SQL remove duplicate rows when counting | [
"",
"sql",
""
] |
I am creating a module for use in DNN 7+ and would like to use DAL2 for data access but am having some problems selecting items from the database.
My code appears to be connecting to the database successfully but the queries that are generated by DAL2 do not include the names of the fields in the database table. I an ... | I found an answer but would like a little help understanding why this works.
First, to get the data column to connect, I changed the Product.cs class to this:
```
using System.Web.Caching;
using DotNetNuke.ComponentModel.DataAnnotations;
namespace MyModule.Components
{
[TableName("Product")]
[PrimaryKey("produ... | RacerNerd,
Needing the proper accessors:
```
public string productCode { get; set; };
```
vs
```
public string productCode;
```
I missed that! Good catch.
I believe the reason for the explicit getter and setters is not only to follow the convention of Entity Framework POCOs, but also I believe when you explicitly... | Why are DAL2 queries missing field names and showing SELECT NULL? | [
"",
"sql",
"data-access-layer",
"dotnetnuke-module",
"irepository",
"dotnetnuke-7",
""
] |
I have a table `orders` with columns `orderid` and `OrderDate`.
I want to get data in batches of 5 years, like total orders between 1990-1995, 1995-2000, 2000-2005 etc in SQL Server.
For example :
```
Period Orders
1990-1995 4500
1995-2000 7000
2000-2005 9000
```
Thanks in advance | I think this is a clear syntax, using one subquery:
```
SELECT CAST(T.YearDivision * 5 AS nchar(4)) + N' - ' + CAST(T.YearDivision * 5 + 4 AS nchar(4)) AS YearRange, SUM(T.TotalCount) AS TotalOrders
FROM
(
SELECT YEAR(Date) / 5 AS YearDivision, Date, COUNT(*) AS TotalCount
FROM Orders
GROUP BY Date
) T
GRO... | you can group by YEAR function - this will do groupping by each year, like:
```
select YEAR(d), sum(...)
from table
group by YEAR(d)
```
if you want to combine several years into one - consider simple math:
```
select FLOOR(YEAR(d)/5)*5, sum(...)
from table
group by FLOOR(YEAR(d)/5)
```
with this group your will ha... | Get data between each 5 year in SQL Server (like 1990-1995, 1995-2000, 2000-2005) | [
"",
"sql",
"sql-server",
""
] |
I'm trying to return the following three columns: Song ID, Song name, Times Played.
This represents a list of requested and played songs.
Assumptions:
1. Table SONG has SONG\_ID and SONG\_NAME, one row for each song
2. Table SONG\_REQUEST only has SONG\_ID for each time the song is requested
3. Table PLAY has SONG\_I... | Something like this should work:
```
SELECT r.SONG_ID, s.SONG_NAME, COUNT(p.SONG_ID) AS TimesPlayed
FROM PLAY p
INNER JOIN SONG s ON p.SONG_ID = s.SONG_ID
LEFT JOIN SONG_REQUEST r ON p.SONG_ID = r.SONG_ID
GROUP BY r.SONG_ID, s.SONG_NAME;
```
Note that in the `group by` clause I've reference the *exact same* columns a... | Oracle doesn't allow to use aliases from the `SELECT` clasuse in the `GROUP BY` clause (you'd need to write `COUNT(p.SONG_ID)` again) but it doesn't make much sense to group by `TimesPlayed` anyway. You probably want to remove it entirely.
Also, you select these columns:
```
r.SONG_ID, s.SONG_NAME
```
... but attemp... | Oracle throwing "invalid identifier" on COUNT() alias within GROUP BY | [
"",
"sql",
"oracle",
""
] |
I have a table for storing coupons/discounts, and I want to use the coupon\_code column as the primary key, which is a `VARCHAR`.
My rationale is that, each coupon will have a unique code, and the only commands I will be running are `SELECT ... FROM ... WHERE coupon_code='..'`
I won't be doing any joins or indexing, ... | Of course you can, in the sense that your RDBMS will let you do it. The answer to a question of whether or not you *should* do it is different, though: in most situations, values that have a meaning outside your database system should *not* be chosen to be a primary key.
If you know that the value is unique in the sys... | A blanket "no you shouldn't" is terrible advice. This is perfectly reasonable in many situations depending on your use case, workload, data entropy, hardware, etc.. What you *shouldn't* do is make assumptions.
It should be noted that you can specify a prefix which will limit MySQL's indexing, thereby giving you some h... | Can I use VARCHAR as the PRIMARY KEY? | [
"",
"mysql",
"sql",
"primary-key",
"unique",
"varchar",
""
] |
I have a table with two columns, name and numb. The first column contains a name and the second contains a number for that name.
What I'm trying to do is output 3 columns, name, number, name, where the last name column is a name that contains the same number as the first name column.
So the output would probably look... | You need to make a `JOIN` on the same table, like this:
```
SELECT t1.name, t1.numb, t2.name AS name2
FROM test t1
JOIN test t2 ON t1.numb = t2.numb AND t1.name <> t2.name
```
See it [live](http://sqlfiddle.com/#!2/ed72b/20)! | You could try something like
```
SELECT *,
(SELECT name FROM test tt WHERE tt.numb = t.numb AND tt.name <> t.name limit 1) nname
from test t;
```
## [SQL Fiddle DEMO](http://sqlfiddle.com/#!2/ed72b/21)
The problem with your idea, can be seen when looking at the second set of rows
```
| NAME | NUMB | NAME |
|-----... | Comparing a column using the data of one column in the same table SQL | [
"",
"mysql",
"sql",
"compare",
""
] |
I am fairly new to SQL so apologies if this questions sounds odd.
I keep coming across the issue of poor data. As an example London could be stored as LON, London UK, London England etc. Prior to using SQL I had lots of Excel lookup tables where in the first column I would have the original, and in the 2nd helper colu... | You don't have to do any of the other things, just return the original if you don't have a translation for it.
```
SELECT
t1.FirstName,
t1.LookupField,
case when t2.Name_1 is null
then t1.lookupfield
else t2.name_1 end Name_1
FROM People as t1
LEFT INNER JOIN TableLookupCities as t2
ON t1.LookupField = t2.Na... | You can join to the lookup table and preferrable use the value given there. If not found, use the original:
```
SELECT t1.FirstName, LookupField = ISNULL(t2.Name_1, t1.LookupField)
FROM People as t1
LEFT INNER JOIN TableLookupCities as t2 ON t1.LookupField = t2.Name
```
Make sure, that for each name there is at most ... | Best Practice For Lookup Tables In SQL | [
"",
"sql",
"sql-server-2008-r2",
""
] |
I've a table named `wp_bp_activity` with many columns that I think I should work with 4 of them for this issue: `id`, `type`, `item_id` and `date_recorded`.
**1 -** When someone post a new activity the `type` is `activity_update` and `item_id` is `0`
**2 -** When someone post a new comment on an activity its `type` i... | I am going to assume that you are looking for "recent entries" (`WHERE type = 'activity_update' AND date_recorded > [threshold]`) and "entries having a recent reply, regardless of the entry's age" (`WHERE reply.type = 'activity_comment' AND reply.date_recorded > [threshold]`).
The first set is straightforward:
```
SE... | Maybe I'm missing something huge but what's wrong with just?:
```
SELECT *
FROM `wp_bp_activity`
WHERE `type`='activity_update'
ORDER BY `date_recorded` ASC
LIMIT 0, 20;
``` | Idea for writing a mysql query | [
"",
"mysql",
"sql",
"wordpress",
""
] |
I have a SQL Server 2005 query where I am using a case statement in the Select statement. I want to know what the "correct" way of doing it is.
Each format seems to work perfectly fine, but I was wondering if there is some redundancy between the different selects or something.
Sample formats:
```
SELECT 'isItemDispl... | This really has nothing to do with the CASE statement. You can create a column alias for any expression in the select list, including simple column names (ie: to re-name to match client code), literal expressions, function calls, etc. But continuing with your CASE example, there are some things to know.
I almost never... | Referencing the example at the bottom of [this](http://technet.microsoft.com/en-us/library/ms188348.aspx) page, I would say:
```
SELECT CASE WHEN ... THEN ... END AS isItemDisplayed FROM myTable
```
because it explicitly defines `isItemDisplayed` as the name.
I personally would prefer:
```
SELECT CASE WHEN ... THEN... | SQL Case Statement Proper Aliasing | [
"",
"sql",
"sql-server-2005",
""
] |
I have 2 tables (`AllClients` & `AllActivities`) and need to retrieve the following information:
I need a list of distinct clients where the most recent activity has been entered in the last year. I've gotten the following code to work, but it is painfully slow and therefore not useful. I believe a join (without the s... | try this:
```
select AllClients.LookupCode
from AllClients
join AllActivities on AllClients.LookupCode = AllActivities.LookupCode
where AllClients.Name = '$userName' and AllClients.TypeCode = 'P'
group by AllClients.LookupCode
having max(AllActivities.EnteredDate) < '$oneYearAgo';
``` | do you mean something like this?
```
SELECT AllClients.LookupCode
FROM AllClients
JOIN AllActivities
ON AllClients.LookupCode = AllActivities.LookupCode
WHERE AllClients.Name = '$userName'
AND AllClients.TypeCode = 'P'
GROUP BY AllClients.LookupCode
HAVING MAX(AllActivities.EnteredDate) < '$o... | Need help improving SQL performance (subquery versus join) | [
"",
"mysql",
"sql",
""
] |
I have data that looks as follows:

I would like to pivot this data so that there is only a single row for the SubId. The columns would be SubId, 802Lineage, 802ReadTime, 1000Lineage, 1000ReadTime etc.
If it wasn't for the requirement to have the Li... | you can pivot manually:
```
select
SubId,
max(case when ProcessNumber = 802 then ReadTime end) as [802Time],
max(case when ProcessNumber = 802 then Lineage end) as [802Lineage],
....
from SourceTable
group by SubId
``` | You can use the PIVOT function to get the result but you will have to unpivot the `Lineage` and `ReadTime` columns from the multiple columns into multiple rows.
Since you are using SQL Server 2012 you can unpivot the data using CROSS APPLY with VALUES:
```
select subid,
colname = cast(processNumber as varchar(10))... | Is it possible to Pivot data like this? | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2012",
"pivot",
""
] |
I am using `Order by` for records sorting. I want to select NULL records at last position in every sorting.
Eg.
```
ASC - {1,2,3,4,5,6,7,NULL,NULL,NULL}
DESC - {7,6,5,4,3,2,1,NULL,NULL,NULL}
```
How to do this in Oracle query? | Your order by clause should be as follows:
desc
```
order by <field_name> desc nulls last;
```
asc
```
order by <field_name> asc nulls last;
``` | Basic MySql Query and Yii2 based Code:
```
Basic Query in MySql:
SELECT *, IF(cloumn_name IS NULL, 1, 0) as cloumn_name_alias FROM `table_name` WHERE 1 ORDER BY cloumn_name_alias, cloumn_name ASC;
For Yii2 Framework:
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' ... | Oracle - Order by column with NULL values in last position | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
My table looks something like this:
```
group date cash checks
1 1/1/2013 0 0
2 1/1/2013 0 800
1 1/3/2013 0 700
3 1/1/2013 0 600
1 1/2/2013 0 400
3 1/5/2013 0 200
```
-- Do not need cash just demonstrating that table has more... | ```
SELECT group,MAX(date) as max_date
FROM table
WHERE checks>0
GROUP BY group
```
That works to get the max date..join it back to your data to get the other columns:
```
Select group,max_date,checks
from table t
inner join
(SELECT group,MAX(date) as max_date
FROM table
WHERE checks>0
GROUP BY group)a
on a.group = ... | You can use a [window](http://msdn.microsoft.com/en-us/library/ms189461%28v=sql.90%29.aspx "OVER Clause (Transact-SQL)") MAX() like this:
```
SELECT
*,
max_date = MAX(date) OVER (PARTITION BY group)
FROM table
```
to get max dates per `group` alongside other data:
```
group date cash checks max_date
---... | Select info from table where row has max date | [
"",
"sql",
"sql-server-2005",
"greatest-n-per-group",
""
] |
Here is what I have:.
```
Con.close()
Con.open()
Query ="Update Products Set QOH = QOH - '" & txtQoH.text & "' Where Prod_ID ='"& textbox1.text & "'"
Command.ExecuteNonQuery()
Con.Close().
```
Okay There, I'm trying to update a product quantity on hand once certain number of product is being purchased. So I've tried... | There are so many problems in your code. Let me start to list them.
* First The field `QOH` is numeric right? So don't try to subtract a
string from a number (The quotes around the textbox)
* Second, you write a query but there is no code that show how do you
set this text in your command
* Third, a connection sho... | Unless you've left out some code, I don't see where you're actually setting the [`CommandText`](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.commandtext.aspx) of the `Command` object:
```
Query ="Update Products Set QOH = QOH - '" & txtQoH.text & "' Where Prod_ID ='"& textbox1.text & "'"
C... | SQL and VB.NET 2008 Query | [
"",
"sql",
"vb.net",
""
] |
I have a SQL Data Project that was created from the schema of my production database. It pulled in all the stored procedures into the project and I am trying to deploy the generated scripts to localdb for offline development.
The Issue is that it appears SQL Data Project is trying to validate the SQL script that it ge... | It seems that the script that SQL Data Tools generates for deployment of the database uses `$()` as a way of doing variable replacement. To correct the issue I had to replace the contents of the string with
`CHAR(36) + '()'`
to represent
`$()`
This way the parser wouldn't try to see it as a variable. | You may try like this:-
```
INSERT INTO mytable (text) VALUES ('''I''''''m Sure this broke things''')
```
If you are inserting from SQL you may also try this:-
```
DECLARE @Value varchar(50)
SET @Value = 'I''m Sure this broke things'
INSERT INTO Table1 (Column1) VALUES (@Value)
```
If you are using ADO.NET then try... | SQL Data Project: Incorrect Syntax '$(' | [
"",
"sql",
"visual-studio-2012",
"escaping",
"localdb",
""
] |
Say I have two tables, `patients` and `rooms`, and `patients` is
```
CREATE TABLE patient (
id int,
room int,
FOREIGN KEY (room) REFERENCES room (id)
);
```
and `room` is
```
CREATE TABLE rooms (
id int,
);
```
I'd like to create a view of `rooms` that includes how many patients are in that room.
I can ... | This will bring all the rooms, with `patientsCount = 0` when they are empty.
```
SELECT r.id roomId, coalesce(count(p.room),0) patientsCount
FROM room r left join patients p on r.id = p.room
GROUP BY r.id
``` | ```
SELECT room, COUNT(*) patients_in_room
FROM patient
GROUP BY room
``` | Calculate a column on select in MySQL | [
"",
"mysql",
"sql",
"database",
""
] |
I have following function which is supposed to check for the number to be 4 digits.
```
function f_checkNum(
@pnum integer
) returns integer
begin
return case
when @pnum like '[0-9][0-9][0-9][0-9]' then 1
else 0
end;
end
```
... | ```
Return CASE WHEN @pnum between 1000 and 9999 Then 1 Else 0 End
```
If you need to include negative numbers then
```
Return CASE WHEN ABS(@pnum) between 1000 and 9999 Then 1 Else 0 End
``` | Try something like this:
```
return case
when LEN(cast(@pnum as varchar)) = 4 then 1
else 0
end;
``` | Checking for number of digits | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have stored procedure that inserts data into table. One column in the table is datetime and is used for storing the time stamp of row insert:
```
INSERT INTO myTable (Field1, Field2, Field3) VALUES (1, 2, GETUTCDATE());
```
`Field3` is datetime column. When I select data from that table with simple `SELECT * FROM m... | You have to be doing something somewhere to change this to smalldatetime or something because it works fine. I just created a new table, inserted data like you showed, queried the table and I have the milliseconds.
I have been unable to find anything where you can set the precision at the server level so it must be in... | As [Steve](https://stackoverflow.com/users/2284256/steve) suggested, issue was not related with server. There is a trigger on this table, that trigger does milliseconds rounding on insert. | Milliseconds from GETUTCDATE not stored in datetime field | [
"",
"sql",
"sql-server",
"datetime",
""
] |
I have two/three state variables stored in DB-table fields and I wonder what's the best way to toggle them (from 1 to 0 and vice versa) and return back their new value.
Running two queries seems too much to me.
Is there another, better way?
Here is my query now (i haven't tested it yet):
```
UPDATE MyTable qrus
SET q... | I don't think what you want is possible. If you desperately want your application to only make one call, you could use a stored function to update and then retrieve (or the other way around, retrieve and then update, doesn't matter). But that's still 2 statements, it's just that the application only makes 1 call. | You can use a sub-query to pull the inverted value and join back to the parent query. Then use a `RETURNING` clause.
```
UPDATE MyTable qrus
SET qrus.favorite = (
SELECT CASE WHEN b.favorite = 0 THEN 1 ELSE 0 END
FROM MyTable b WHERE grus.PK_FIELDS =b.PK_FIELDS
)
WHERE grus.PK_FIELDS = :pkFields
RETURNING grus.fa... | Oracle : toggle field and return the new value | [
"",
".net",
"sql",
"oracle",
""
] |
This is what I've done.
```
create proc INITCAP(@string varchar(30))
as
begin
SET @string = UPPER(LEFT(@string,1)) + LOWER(RIGHT(@string, LEN(@string) -1))
end
declare @lastname varchar
set @lastname = exec INITCAP 'MILLER'
declare @firstname varchar
set @firstname = exec INITCAP 'StEvE'
UPDATE Employee SET fir... | **Solution #1** (I wouln't use this solution)
You could use OUTPUT parameters thus:
```
create proc INITCAP(@string varchar(30) OUTPUT)
as
begin
SET @string = UPPER(LEFT(@string,1)) + LOWER(SUBSTRING(@string, 2, 8000))
end
go
declare @lastname varchar
set @lastname = 'MILLER'
exec INITCAP @lastname OUTPUT
decl... | Do you really need a stored Proc for this ??? I would do something like this a UDF would do the job just fine i think....
```
CREATE FUNCTION dbo.udf_SomeFunction (@String VARCHAR(30))
RETURNS VARCHAR(30)
AS
BEGIN
DECLARE @rtnString VARCHAR(30);
SET @rtnString = UPPER(LEFT(@string,1)) + LOWER(RIGHT(@string, L... | SQL Server : return string procedure INITCAP | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
I have the following table's in my SQL database.
```
DIM_BENCHMARK:
Fund_sk | Num_Bench | Bench | Weight | Type_Return
1 2 XXX 0.9 TR
1 2 YYY 0.1 Net
2 3 XXX 0.45 TR
2 3 YYY 0.45 TR
2 3... | Your main problem is your fact table. It is not normalised properly - you should have one row for each value.
The `unpivot` in the below SQL normalises the data.
```
select
[date], fund_sk,Num_Bench, sum(weight * val)
from
(
select *
from fact_returns
unpivot (val for type in (tr, net)) u
) ... | This should solve the issue and would also work in any DBMS:
```
SELECT fr.date, db.fund_sk, db.num_bench, sum(db.weight *
CASE db.type_return
WHEN 'TR' THEN fr.tr
WHEN 'Net' THEN fr.net
ELSE 0
END) Bench_Returns
FROM dim_benchmark db
JOIN fact_returns fr ON db.bench = fr.bench
GROUP BY fr.date, db.fun... | Dynamic Column Selection SQL | [
"",
"sql",
"sql-server",
"ssis",
"dynamic-programming",
""
] |
In a Mysql database with every table based on InnoDB with Autocommit enabled, will queries with subqueries and/or joins be atomic?
Examples:
* `INSERT INTO users SELECT (x,y,z) FROM users, comments WHERE users.id = comments.user_id;` (joins)
* `UPDATE users, comments SET users.x = x1 WHERE users.age > 30;` (joins)
* ... | I understand your question like "is each of those queries in itself an atomic operation?". Then the answer is "yes".The other two answers are right, when they say that all your statements together are not atomic.
Atomicity in databases **only means** all or nothing. It **does not mean** correctness of data. Your state... | No. Unless you wrap them in `START TRANSACTION` like this
```
START TRANSACTION;
SELECT @A:=SUM(salary) FROM table1 WHERE type=1;
UPDATE table2 SET summary=@A WHERE type=1;
COMMIT;
```
Example from [Mysql manual](http://dev.mysql.com/doc/refman/5.5/en/commit.html) | Is join insert/update on MySQL an atomic operation? | [
"",
"mysql",
"sql",
"concurrency",
"locking",
"atomic",
""
] |
I have the tables:
```
contest_images {contestID, imageID}
image {ID, userID}
user {ID}
```
(They contain more information than that, but this is all we need)
My query so far:
```
SELECT imageID, userID FROM contest_images
JOIN image ON contest_images.imageID = image.ID
JOIN user ON user.ID = image.userID
ORDER BY... | Try like this,
```
SELECT MAX(imageID), userID FROM contest_images
JOIN image ON contest_images.imageID = image.ID
JOIN user ON user.ID = image.userID
GROUP BY image.userID
``` | To limit to one image/ latest image in contest at a time you can use Top operator as :
```
SELECT top 1 imageID, userID FROM contest_images
JOIN [image] ON contest_images.imageID = [image].ID
JOIN [user] ON [user].ID = image.userID
ORDER BY contest_images.imageID DESC
``` | SQL Query I can't figure out | [
"",
"mysql",
"sql",
""
] |
I have a table "Customers" with columns `CustomerID`, `MainCountry` and `CustomerTypeID`.
I have 5 customer types 1,2,3,4,5 .
I want to count number of customers of each country according to customer type. I am using the following query:
```
select count(CustomerID) as CustomerCount,MainCountry,CustomerTypeID
from ... | ```
Select Country.MainCountry, CustomerType.CustomerTypeId, Count(T.CustomerID) As CustomerCount
From (Select Distinct MainCountry From Customers) As Country
Cross Join (Select Distinct CustomerTypeId From Customers) As CustomerType
Left Join Customers T
On Country.MainCountry = T.MainCountry
... | You should JOIN your table with a table with TypeId's. In this case
```
select count(CustomerID) as CustomerCount,TypeTable.MainCountry,TypeTable.TId
from
Customers
RIGHT JOIN (
select MainCountry,TId from
(
select Distinct MainCountry from Customers
) as T1,
... | sql query to get data group by customer type and need to add default value if customer type not found | [
"",
"sql",
"sql-server",
""
] |
I'm trying to write a complex query using PostgreSQL 9.2.4, and I'm having trouble getting it working. I have a table which contains a time range, as well as several other columns. When I store data in this table, if all of the columns are the same and the time ranges overlap or are adjacent, I combine them into one ro... | First off, your upper border concept is *broken*. A timestamp with `23:59:59` is no good. The data type `timestamp` has fractional digits. What about `2013-10-18 23:59:59.123::timestamp`?
**Include** the lower border and **exclude** the upper border everywhere in your logic. Compare:
* [Calculate number of concurrent... | There is simply solution (if intervals starts in same time)
```
postgres=# select i, i + interval '1day' - interval '1sec'
from generate_series('2013-01-01 00:00:00'::timestamp, '2013-01-02 23:59:59', '1day') g(i);
i │ ?column?
─────────────────────┼─────────────────────
2013-01-01 0... | PostgreSQL splitting time range into days | [
"",
"sql",
"postgresql",
"date-range",
"generate-series",
""
] |
```
SELECT [schoolname] AS combinationschools,
CASE
WHEN [schoolname] LIKE '%/%' THEN (SELECT value
FROM
[dbo].[Split]('/', '#6/#9E/#9M'))
END AS schoolname
FROM [dbo].[schools];
```
i'm getting q sql error like wise-
> Subqu... | When you use a subquery like this, you can only have one record in the result set for each record. Clearly your table Split has more than one record.
Use a join instead of a subquery. Or make this a correlated subquery by joining it to the schools table in the subquery or pull only the Max or min record or make some s... | That's because `Select value from [dbo].Split` is returning more than one value. | "Subquery returned more than 1 value" error | [
"",
"sql",
"sql-server",
""
] |
I'm having trouble coming up with a way to compare some data in SQL Server (2005). I have two tables and I need to make sure that the values from table 1 are matched in table two. Here's the table structure and some example data.
```
Table 1
GenreId
6
```
This is a temp table with a list of IDs that are passed in.
... | This is the query you're looking for:
```
SELECT SHOW FROM t2
WHERE SHOW NOT IN (
SELECT SHOW FROM t2
WHERE genreId NOT IN (6, 2)
)
GROUP BY SHOW
HAVING count(DISTINCT genreId) = 2
```
Those queries are a bit tricky. Take into account that the number in the `HAVING` clause have to match the AMOUNT of items in the... | Well, this should work but it may have horrible performance if `Table2` is large...
```
SELECT * FROM Table2 t2
WHERE NOT EXISTS(
SELECT GenreID
FROM Table1
WHERE GenreID NOT IN (
SELECT GenreID
FROM Table2
WHERE Show = t2.Show))
AND NOT EXISTS(
SELECT GenreID
FROM Table... | How to query two tables to compare data | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
This is a follow on question from @Erwin's answer to [Efficient time series querying in Postgres](https://stackoverflow.com/a/14877465/79790).
In order to keep things simple I'll use the same table structure as that question
```
id | widget_id | for_date | score |
```
The original question was to get score for each ... | As [@Roman mentioned](https://stackoverflow.com/a/19443336/939860), `DISTINCT ON` can solve this. Details in this related answer:
* [Select first row in each GROUP BY group?](https://stackoverflow.com/questions/3800551/select-first-row-in-each-group-by-group/7630564#7630564)
Subqueries are generally a bit faster than... | Like you wrote, you should find matching score, but if there is a gap - fill it with nearest earlier score. In SQL it will be:
```
SELECT d.day, w.widget_id,
coalesce(s.score, (select s2.score from score s2
where s2.for_date<d.day and s2.widget_id=w.widget_id order by s2.for_date desc limit 1)) as score
from (s... | Time series querying in Postgres | [
"",
"sql",
"postgresql",
"time-series",
"greatest-n-per-group",
"generate-series",
""
] |
This is a simplified version of my problem.
I have table like below
```
Id Name SNumber
100 XYZ 123
100 XYZ 123
101 ABC 123
103 QAZ 123
100 XYZ 971
100 XYZ 872
100 XYZ 659
102 PQR 145
102 PQR 707
103 QAZ 421
```
I want to count r... | Try this:
```
SELECT id, name,
COUNT(CASE WHEN SNumber = 123 THEN 1 END) Total,
COUNT(CASE WHEN SNumber <> 123 THEN 1 END) OtherTotal
FROM t
GROUP BY id, name
ORDER BY id
```
Fiddle [here](http://sqlfiddle.com/#!6/ce7a2/1). | ```
select
Id, Name,
sum(case when SNumber = 123 then 1 else 0 end) as Total,
sum(case when SNumber <> 123 then 1 else 0 end) as OtherTotal
from Table1
group by Id, Name
order by Id
```
or
```
select
Id, Name,
count(*) - count(nullif(SNumber, 123)) as Total,
count(nullif(SNumber, 123)) as Othe... | Retrieve matching rows using join | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2005",
""
] |
```
Select GroupId,
count(distinct GroupProgramYearParticipantID)as [ChildAddedprior]
from #temp1
Where (MonthFlag = '1')
and (ParticipantTypeName = 'child')
and (GroupProgramYearParticipantID not in
(Select distinct GroupProgramYearParticipantID
from #... | ```
SELECT GroupID, COUNT(Distinct GroupParticipantID) AS CNT
FROM #Temp1 A
WHERE A.GroupParticipantID NOT IN
(
SELECT GroupParticipantID
FROM #Temp1 B
WHERE A.GroupID > B.GroupID
)
Group BY GroupID
```
**[SQL Fiddle Demo](http://sqlfiddle.com/#!6/b95ae/5)** | You could use 2 queries to achieve that.
1. Select the first group's ids into a temp table.
2. When selecting the second group, don't select ids that exist in the temp table.
Alternatively, you can take the results of your query (ids) and use common table expressions to count groups recursively starting from the firs... | Count only the id's which are not counted in earlier group | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Let's say you have a table with columns A and B, among others. You create a multi-column index (A, B) on the table.
Does your query have to take the order of indexes into account? For example,
```
select * from MyTable where B=? and A in (?, ?, ?);
```
In the query we put B first and A second. But the index is (A, B... | In this case no but I recommend to use the [EXPLAIN](http://dev.mysql.com/doc/refman/5.1/en/using-explain.html) keyword and you will see which optimizations MySQL will use (or not). | The order of columns in the index can affect the way the MySQL optimiser uses the index. Specifically, MySQL can use your compound index for queries on column A because it's the first part of the compound index.
However, your question refers to the order of column references in the query. Here, the optimiser will take... | Does the order of indexes matter? | [
"",
"mysql",
"sql",
""
] |
I am trying to assign 'A' to [Student Details].group based on this SELECT statement.
```
SELECT TOP (10) PERCENT [Person Id], [Given Names], Surname, Gpa, [Location Cd]
FROM [Student Details]
WHERE ([Location Cd] = 'PAR')
ORDER BY Gpa DESC
```
I can't figure out how to use a SELECT statement in an UPD... | Try this using `CTE` (Common Table Expression):
```
;WITH CTE AS
(
SELECT TOP 10 PERCENT [Group]
FROM [Student Details]
WHERE ([Location Cd] = 'PAR')
ORDER BY Gpa DESC
)
UPDATE CTE SET [Group] = 'A'
``` | I'm assuming you want to update these records and then return them :
```
SELECT TOP (10) PERCENT [Person Id], [Given Names], Surname, Gpa, [Location Cd]
INTO #temp
FROM [Student Details]
WHERE ([Location Cd] = 'PAR')
ORDER BY Gpa DESC
update [Student Details] set group='A' where [person id] in(select [person id] ... | Update multiple rows from select statement | [
"",
"asp.net",
"sql",
""
] |
Is it possible to `SELECT` the minimum or maximum among two or more values. I'd need something like this:
```
SELECT MAX_VALUE(A.date0, B.date0) AS date0, MIN_VALUE(A.date1, B.date1) AS date1
FROM A, B
WHERE B.x = A.x
```
Can I achieve this by only using MySQL? | You can use `LEAST` and `GREATEST` function to achieve it.
```
SELECT
GREATEST(A.date0, B.date0) AS date0,
LEAST(A.date1, B.date1) AS date1
FROM A, B
WHERE B.x = A.x
```
Both are described here <http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html> | I suppose you are looking for:
[`GREATEST()`](http://dev.mysql.com/doc/refman/5.6/en/comparison-operators.html#function_greatest)
and
[`LEAST()`](http://dev.mysql.com/doc/refman/5.6/en/comparison-operators.html#function_least) | MySQL Select minimum/maximum among two (or more) given values | [
"",
"mysql",
"sql",
""
] |
I'm developing an ecommerce website, but i got confius with the database design.
I have 3 tables:
1. Products (id, category\_id, subcategory\_id, name)
2. Categories (id, name)
3. Subcategories (id, category\_id, name)
For example: Product (Stripped Tshirt) is in Category (Fashion) and Subcategory (Tshirt)
What if ... | Firstly, I would not have a category ID and subcategory ID on the product. It only belongs to a subcategory. You can find out the parent category through the subcategory if you need to.
```
products (id, subcategory_id, name)
categories (id, name)
subcategories (id, category_id, name)
```
For the attributes which c... | Magento, which is a huge shop solution, solves this using [EAV](http://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model). EAV is flexible but does not perform as good as a dedicated table solution.
Your Category -> Subcategory does not make much sense. Read about nested sets or use a pure parent-chil... | Cakephp database design for ecommerce | [
"",
"mysql",
"sql",
"cakephp",
"size",
"product",
""
] |
Not sure if I have phrased the title properly, but here it goes. I have these two tables:
table:staff
```
id Name groupId Status
1 John Smith 1 1
2 John Doe 1 1
3 Jane Smith 2 1
4 Jerry Smith 1 1
```
table:jobqueu... | not sure that it is optimal query, but it works:
```
select d.groupId, d.name, (select count(*) from jobqueue as e where e.staff_id=d.id) as jobassigned
from staff as d
where d.id in (
select
(
select a.id
from staff as a
left outer join
jobqueue as b
on (a.id = b.s... | ```
with
counts as (
select s.groupId
, s.id
, (select count(*) from jobqueue where staff_id = s.id) count
from staff s
group by s.id, s.groupId),
groups as (
select groupId, min(count) mincount
from counts
group by groupId)
select c.groupId, c.id, c.count
from counts c
join groups g on ... | Mysql (conditional?) query from two tables | [
"",
"mysql",
"sql",
"yii",
""
] |
Cant seem to figure this one out...
I have a table, one of the fields is variabletype. There are several user input variable types. For example:
```
id | variabletype
1 | button
2 | text
3 | button
4 | link
5 | button
6 | link
```
I wrote some SQL to basically count the number of times each variable type is li... | Try this :
```
SELECT `variabletype `,
COUNT(`variabletype `) AS `value_occurrence`
FROM `my_table`
GROUP BY `value`
ORDER BY `value_occurrence` DESC
LIMIT 1;
``` | If row\_number function is avialable in your SQL environment then you can do the following:
```
SELECT y.variabletype, y.mosttested as max_mosttested
FROM (SELECT variabletype, COUNT(variableid) AS mosttested, row_number()over(order by count(variableid) desc)
FROM variable GROUP BY variabletype) y
where rownum... | Returning field name when using Max and Count queries | [
"",
"mysql",
"sql",
""
] |
I have a requirement to round a datetime2 value down to the nearest half hour. For example '10/17/2013 12:10:00.123' would round down to '10/17/2013 12:00:00.0' And '10/17/2013 12:34:17.123' would round down to 10/17/2013 12:30:00.0'. My first thought was to create a UDF which would break the date and time apart and do... | The answer by Ian is good, but it contains an unnecessary conversion. I suggest
```
SELECT CONVERT(smalldatetime, ROUND(CAST([columnname] AS float) * 48.0,0,1)/48.0) FROM [tableName]
```
If you want to round to the nearest half-hour instead of always rounding down, use
```
SELECT CONVERT(smalldatetime, ROUND(CAST([c... | How about this
```
declare @d datetime = '2013-05-06 12:29.123'
select
case
when datepart(minute, @d) < 30 then cast(dateadd(minute, -datepart(minute,@d)-datepart(second,@d), @d) as smalldatetime)
when datepart(minute, @d) >= 30 then cast(dateadd(minute, -datepart(minute,@d)-datepart(second,@d)+30, @d) as sm... | Rounding a datetime value down to the nearest half hour | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I get an error in the query below. Why ?
```
DECLARE @Vr varchar(50);
SET @Vr = N'Infos';
IF @Vr = FAR
UPDATE MyTable
SET TAR = @Vr
```
Error - Invalid column name 'FAR'.
I am using the right database and right table. Then, why does this happen ?
My logic is if Column Far = variable Vr, then update Column TAR. | In your case, you are checking the column name and not that particular column's value. I suggest you try dynamic sql. This [link](http://www.codeproject.com/Articles/20815/Building-Dynamic-SQL-In-a-Stored-Procedure) can be useful.
As far as I've understood, if your `@Vr = 'FAR'` then update field `TAR` else do somethin... | ```
DECLARE @Vr varchar(50);
SET @Vr = N'Infos';
-- IF @Vr = FAR
IF ( select Count(*) from mytable where ColumnFar =@Vr) >0
BEGIN
UPDATE MyTable
SET TAR = @Vr where ColumnFar =@Var
END
ELSE
BEGIN
-- Goes your condition
END
```
Or use CASE
```
DECLARE @Vr varchar(50);
SET @Vr = ... | Error in if else in sql | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a database with some tables, each with `ID` primary key column. All `ID`s contain huge random numbers like `827140014`, `9827141241`, etc. What is the easiest way to edit and change this values for chronological, starting from 1 (`1`, `2`, `3`, etc.)? Rows' order doesn't matter.
I want to do it for SQL Server, ... | Oracle solution: given table some\_table with column id as primary key:
```
CREATE TABLE my_order AS SELECT id, rownum rn FROM some_table;
ALTER TABLE my_order ADD CONSTRAINT pk_order PRIMARY KEY (id);
UPDATE
(SELECT t.*, o.rn FROM some_table t JOIN my_order o on (t.id = o.id))
SET id = rn;
DROP TABLE my_order;
``... | For Oracle
a). If there are tables referencing the table you want to update, first thing you have to do is to disable foreign key constraints. You can generate all the `ALTER` statements using below query:
```
SELECT 'ALTER TABLE ' || owner || '.' || table_name ||
' DISABLE CONSTRAINT ' || constraint_name || '... | Massive primary key edition for disordered primary key column | [
"",
"sql",
"sql-server",
"oracle",
"sqlite",
"postgresql",
""
] |
The search term is to ambiguous for google aparently. I am looking at a SQL call and it has 2 FROM keywords? I've never seen this before, can someone explain?
```
SELECT TOP(5) SUM(column) AS column, column
FROM ( SELECT DISTINCT column, column, column
FROM ((((((table table
INNER JOIN table table ON (column = colum... | This is called as `subquery`. You can use `subquery` within your main query
So subquery made the multiple FORM clause. | There's a reason why SQL is called a **Structured** Query Language: it lets you formulate queries that use other queries as their source, thus creating a hierarchical query structure.
This is a common practice: each `FROM` keyword is actually paired with its own `SELECT`, making the inner query a source for the outer ... | SQL Server - Multiple FROM keywords? | [
"",
"sql",
"sql-server",
""
] |
Lets say i have a table that has the following columns
(Start, End, Interval)
Is there any way to get all values between Start, End with the interval each on one row?
Notice that will be more then one row in the (Start, End, Interval) table but they should not overlap.
If possible without loops/cursors/temp tables/va... | This is a great use case for a recursive common table expression:
```
;with cte as (
select [Start] as Result, [End], [Interval]
from Table1
union all
select Result + [Interval], [End], [Interval]
from cte
where Result + [Interval] <= [End]
)
select Result
from cte
order by Result
```
**`sql f... | You can do it like this
```
WITH tally AS (
SELECT 0 n
UNION ALL
SELECT n + 1 FROM tally WHERE n < 100 -- adjust 100 to a max possible value for (end - start) / interval
)
SELECT start + n * [interval] result
FROM Table1 t CROSS JOIN tally n
WHERE n.n <= (t.[end] - t.start) / t.[interval]
ORDER BY result
```... | SELECT all values between two values | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2008-r2",
""
] |
I have 2 tables with both of them having the first column as PRIMARY which is also an auto incrementing. First table has 67 entries starting from 1 to 67 and the second table has 48 entries. Both of them have same columns. I want to take the content from Table2 and insert them into Table1 such that the next entry in Ta... | Name the columns you want to insert and leave the auto\_incrment columns from the insert
```
INSERT INTO `Table1` (col2, col3, col4)
select col2, col3, col4 from `table2`
``` | You need to specify the columns you wish to enter, without the identity column.
Something like
```
INSERT INTO `Table1` (column1, column2,...,columnn)
SELECT column1, column2,...,columnn FROM `Table2`
``` | Join 2 tables with same PRIMARY key that is autoincrementing too | [
"",
"mysql",
"sql",
"sql-server",
""
] |
**This is TERADATA** (not SQL Server, not Oracle )
I have a column of phone numbers:
```
(312)9879878
(298)989-9878
430-394-2934
394s9048ds987
..........
```
I need to clean this column into
```
3129879878
2989899878
4303942934
3949048987
..........
```
So that only numbers should stay. All other letters, special ... | Which release of TD is running at your site?
If it's 14 or you got the oTranslate UDF installed you can simply do an old trick nesting Translate:
```
oTranslate(phonenum, oTranslate(phonenum, '0123456789', ''), '')
``` | **Answer :**
> DECLARE @Input varchar(1000)
>
> SET @Input = '01 vishal 98-)6543'
>
> DECLARE @pos INT
>
> SET @Pos = PATINDEX('%[^0-9]%',@Input)
>
> WHILE @Pos > 0
>
> BEGIN
>
> ```
> SET @Input = STUFF(@Input,@pos,1,'')
>
> SET @Pos = PATINDEX('%[^0-9]%',@Input)
> ```
>
> END
>
> SELECT @Input
**Thank You,
Vishal P... | How to replace all nonnumeric values? | [
"",
"sql",
"teradata",
""
] |
```
SELECT * FROM table t
SELECT t.* FROM table t
```
I tried it and it yielded the same results, but I want to make sure because I'm refactoring a piece of code that uses the second version, and I was surprised as it is both longer to write, and less simple.
Are there any hidden stuff here?
MySQL version: 5.5.29-0u... | Both statements are the same in your case.
They would be not if you join multiple tables in one query.
```
select *
```
selects **all** columns.
```
select t.*
```
select all columns **of table t** (or the table assigned the alias t) | ```
SELECT * FROM table t and SELECT t.* FROM table t
```
Return the whole table
`SELECT t.* FROM table as t inner join table2 as t2`
will only return the fields in the "table" table while
`SELECT * FROM table as t inner join table2 as t2`
will return the fields of table and table2 | Are there any differences in the following sql statements? | [
"",
"mysql",
"sql",
""
] |
In this scenario, I am trying to report on the operating\_system\_version for each distinct computer\_id where the report\_id for that computer\_id is the greatest.
Currently, I am getting the below results:
```
operating_system_version | computer_id | report_id
10.8 | 1 | 10
10.9 | 1 | 20
10.9 | 2 | 11
10.8 | 2 | 21... | You would need to add a group by statement and a having statement.
The group by would look like
```
group by computer_id
```
The having would look like
```
having report_id= (select max(report_id) )
``` | ```
SELECT operating_systems.operating_system_version,
reports.computer_id,
reports.report_id
FROM operating_systems INNER JOIN reports ON operating_systems.report_id = reports.computer_id
WHERE NOT EXISTS (SELECT 1
FROM reports r2
WHERE r2.computer_id = reports.... | MySQL: How to limit results to max value of another field? | [
"",
"mysql",
"sql",
"greatest-n-per-group",
""
] |
I am trying to make a change to one of the tables in our database named `NonConf`. Currently, we have three ***Yes/No*** fields called `Closed`, `Open`, and `OnHold`. We are going to be adding more statuses and I think it is a bad idea to continue adding fields for the new statuses. Instead I would like to convert the ... | You can use a [Switch](http://office.microsoft.com/en-us/access-help/switch-function-HA001228918.aspx) expression instead of nesting multiple `IIf` expressions.
```
UPDATE NonConf AS N
SET N.Status =
Switch
(
N.Closed, "Closed",
N.Open, "Open",
N.OnHold,"OnHold",
... | You can use one query to update the `Status` in one shot via a nested `IIF`:
```
UPDATE NonConf AS N
SET N.Status =
IIF (N.Closed, "Closed",
IIF(N.Open, "Open",
IIF(N.OnHold,"OnHold","")))
``` | Combine three fields into one | [
"",
"sql",
"ms-access",
"sql-update",
""
] |
I have two tables in my sqlite db - tenders and lots.
tenders:
```
id
name
address
```
lots:
```
id
tender_id # it's tender's ID from table `tenders`
summ
```
One tender may have many lots. How to count tenders that have 0 lots?
I tried queries such as:
```
select lots.* from lots
inner join tenders on tenders.i... | ```
SELECT tenders.id
FROM tenders
WHERE tenders.id NOT IN (SELECT tender_id FROM lots)
```
or different amounts of lots:
```
SELECT tenders.id
FROM tenders
WHERE tenders.id IN
(
SELECT tender_id FROM lots GROUP BY tender_id HAVING COUNT(*) IN (2,3)
)
``` | Using sub-query:
```
SELECT id, (SELECT COUNT() FROM lots WHERE tender_id=tenders.id) AS LotCount FROM tenders;
``` | How to count child rows? | [
"",
"sql",
"sqlite",
""
] |
I am trying to perform the following query in SQL server:
```
declare @queryWord as nvarchar(20) = 'asdas'
SELECT * FROM TABLE_1
WHERE (ISDATE(@queryWord) = 1)
AND TABLE_1.INIT_DATE = CONVERT(Date, @queryWord)
```
This obviously causes an error because `'asdas'` cannot be converted to `Date`. Although, I was expe... | SQL Server does not do short-circuiting (nor should it).
If you need it to not *try* something under some circumstances, you need to force that in the way that you write your query.
For this query the easiest fix would be to use a `CASE` expression in your `WHERE` clause.
```
declare @queryWord as nvarchar(20) = 'as... | I Guess you could do it in 2 passes:
```
declare @queryWord as nvarchar(20) = 'asdas'
select
*
from
(
SELECT * FROM TABLE_1
WHERE (ISDATE(@queryWord) = 1) ) t1
where t1.INIT_DATE = CONVERT(Date, @queryWord)
```
So your inner query runs the first test and the outer query the second. In ... | How to Short-Circuit SQL Where Clause | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I am a novice Oracle user. I wanted to update a boolean field in my table for one of the record. Which one of these statements is correct ?
```
update MyTable set myBooleanColumn = 1 where UserId= 'xx12345';
or
update MyTable set myBooleanColumn = '1' where UserId= 'xx12345';
```
any help is greatly appreciated!!... | It depends on how the field is defined.
If its defined as a CHAR(1) field, then you can store 'Y'/'N' or 'T'/'F' in it. To update the field, you'd use the quotes as it would be a string literal.
```
UPDATE TestTable set myCharBooleanColumn = 'Y';
```
If the field is defined as NUMERIC, then the convention is 0=false... | There is no such thing as a Boolean field in Oracle so your field is either a numeric field or a character field. If it's a numeric field you don't need to quote the number; if it's a character field you should quote the string.
You can find out the type of the column by querying [USER\_TAB\_COLUMNS](http://docs.oracl... | How to update a boolean field in Oracle table | [
"",
"sql",
"oracle",
"oracle11g",
"oracle10g",
"sql-update",
""
] |
I'm designing a database and I have a question about how to make private some user data.
I have a user table, with name, city, birthday, biography, etc. And the user can make some data private (*other users can see that data*).
First, I thought to add columns to the table to indicate if a column is private or not. Fo... | Do not move data into a separate table if you are going to have to join to it every time you query the main table.
Boolean (or equivalent) columns to indicate privacy for every column on which a privacy setting can be applied:
1. is very simple to add.
2. takes up practically no space.
3. is much quicker to query.
4.... | Move the list of you private columns to separate table whith three fields, like:
```
UserId |ColumnName |IsPrivate
-----------------------------
```
Then you can join your queries with that table and get proper result set for each user, and at the same time change the columns of yor user table.
If your User table wo... | DB Design: how to indicate if a column data is public or private | [
"",
"sql",
"database",
"database-design",
""
] |
Suppose I had the following table in my oracle DB:
```
ID: Name: Parent_ID:
123 a 234
345 b 123
234 c 234
456 d 345
567 e 567
678 f 567
```
And what I would like to do is find, for each `ID` the `ULTIMATE parent ID` (described as row, that when ... | I think the CONNECT\_BY\_ROOT is what you need:
```
select x.*, t2.name ultimate_name
from
(
select t.id, t.name, CONNECT_BY_ROOT parent_id ultimate_id
from toto t
start with t.id = t.parent_id
connect by nocycle prior id = parent_id
) x, toto t2
where x.ultimate_id = t2.id
;
```
This gives:
```
456 d 234 ... | Please try this one:
```
SELECT ID, Name, Parent_ID as Ult_Parent_ID,
(SELECT Name from MyTable t2 WHERE t2.ID = t1.Parent_ID) as Ult_Parent_Name,
LEVEL
FROM MyTable t1
CONNECT BY NOCYCLE Parent_ID = PRIOR ID
START WITH Parent_ID = ID;
```
I believe that we have to use `NOCYCLE` because of how your roots are ... | Oracle Connect By Prior for Recursive Query Syntax | [
"",
"sql",
"oracle",
"recursive-query",
""
] |
I am trying to convert from one date format to another. I am not sure how to write the functions.
My source date looks like `01/15/2009 01:23:15`
The format I need is `01152009`.
Thanks | Try this.
```
TO_CHAR(TO_DATE('01/15/2009 01:23:15','MM/DD/YYYY HH:MI:SS'),'MMDDYYY')
```
More info here,
<http://psoug.org/reference/date_func.html> | ```
select TO_CHAR(TO_DATE('01/15/2009 01:23:15','MM/DD/YYYY MI:HH:SS'),'MMDDYYYY') from dual
```
if your field is already of data type date then you should only do:
```
select TO_CHAR(<fieldname>,'ddmmyyyy') ...
``` | How do I convert this oracle date | [
"",
"sql",
"oracle",
""
] |
I have the following exclude that brings back all of books that have had transactions in the past two minutes. I want to add another constraint that says only if from a series of stores.
In SQL it would be where location\_id = 1 or location\_id = 2 or location\_id = 3
Books have a location\_id
How can I apply that t... | You probably just want `location__in=(1, 2, 3)` | From your code assuming `Book` model has field `book_id` and `Status` has also field `book_id` and this field are just plain `IntegerField` or similar.
```
from django.db.models import Q
transaction_window = timezone.now() - datetime.timedelta(minutes=2)
statuses = Status.objects.filter(transaction_time__gte=transac... | how to add OR constraints to exclude query in django? | [
"",
"sql",
"django",
"django-models",
"django-orm",
""
] |
I have a gender column
```
gender
```
Using MS SQL Server 2012
currently it is smallint which is 2 bytes -2^15 (-32,768) to 2^15-1 (32,767)
and works like follows
```
1 = male
0 = female
-1 = not specified
```
we do a lot of queries on this type of field. and the issues I have are
1. Its not intuitive as to what... | We (EHR software) store as a 1 byte char, as it is concise and easier to understand while working with lots of demographic data.
The possible values map as follows:
* `U` - unknown or unspecified
* `M` - male
* `F` - female
* `NULL` - person hasn't been asked/no value on record.
For us, it is important to note if th... | The much better way, in general, to do things list this is to use a domain or lookup table.
If your attribute is required, it should be non-nullable. If it is not-required, it should be nullable. `Null` means that the data is missing; the user didn't answer the question. It is a different value than an affirmative ans... | Gender Storage and data types | [
"",
"sql",
"sql-server",
""
] |
I have a table that has the following column (with some sample entries provided):
```
COLUMN NAME: pt_age_old
20 Years 8 Months 3 Weeks
1 Year 3 Months 2 Weeks
58 Years 7 Months
1 Year
7 Years 11 Months 2 Weeks
26 Years 6 Months
56 Years 6 Months
48 Years 6 Months 4 Weeks
29 Years 11 Months
4 Years 3 Months
61 Years ... | This could be done using custom code such as below - I've assumed the values you're using are people's ages, and you're trying to work out their date of birth given their age today.
You can see the below code in action here: <http://sqlfiddle.com/#!3/c757c/2>
```
create function dbo.AgeToDOB(@age nvarchar(32))
return... | Technically it is possible to convert the relative time label into a datetime, but you will need a reference date though (20 Years 8 Months 3 Weeks as of '2013-10-16'). The reference date is most likely today (using GETDATE() or CURRENT\_TIMESTAMP), but there is a chance it is a different date. You will have to parse t... | TSQL - converting date string to datetime | [
"",
"sql",
"t-sql",
""
] |
I have an ASP .NET 4.5 application. On a maintenance page is a text box which allows administrative users to write SQL which is executed directly against the SQL Server 2008 database.
Occasionally one of the administrative users writes some inefficient SQL and the SQL Server process starts using up all the memory and ... | You can set the query governor at the server level but not sure about a per user or per connection / application limit.
<http://technet.microsoft.com/en-us/magazine/dd421653.aspx>
That said, it is likely a poor / dangerous practice to allow users to directly enter SQL queries. | First off I would make sure these queries are not locking any tables (either use NOLOCK or SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED for each query ran).
As far as resources go, I would look at something like the Resource Governor. We use this for any adhoc reports on our production OLTP system.
Pinal Dave has... | How can inefficient SQL queries be prevented from slowing a database server | [
"",
"asp.net",
"sql",
"sql-server",
"performance",
""
] |
Is there a way to check the integrity of a SQL Server database? I have these developers (OK, me included) that constantly change objects in our database (views/functions/stored procs) and sometimes we change signatures of objects or drop objects and other objects become invalid/uncompilable. I would like to get some so... | I think what you need is database unit tests that can then be executed through CruiseControl.NET. I recommend using tSQLt (<http://tsqlt.org>). RedGate also sells a nice GUI over the top of this product, but is not required to get the functionality that you need.
(<http://www.red-gate.com/products/sql-development/sql-t... | Olla Hallengran provides an excellant way to check the Integrity of databases.
Please refer
<http://ola.hallengren.com/sql-server-integrity-check.html> | Automatically checking the integrity of the SQL Server Database | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2008-r2",
""
] |
I have two SQL tables, call them t1 and t2. Both have column names str\_id. The str\_id is typically a 10 digit string, but I have special str\_ids that begin with 'sp' followed by a normal 10 digit str\_id. I would like to select all the 'sp' str\_ids from t1, remove the sp, and look up the str\_id in t2. I tried this... | Show the `EXPLAIN` outputs of those two, but I assume with the normal one mysql is able to directy crossreference indexes, while the `SUBSTR` one requires creating an intermediate resultset, and checking each individual item from t2. Which is a nice example why prefixing values with significant data is about as bad as ... | Edited my answer. Try running this instead
```
SELECT str_id,
(
SELECT desired_column
FROM t2
WHERE str_id = SUBSTR(t1.str_id, 3)
)
FROM t1
WHERE str_id LIKE 'sp%' AND other_column = 'my_value'
``` | SQL works fine until I add a SUBSTR to subquery, then it just hangs. Why? | [
"",
"mysql",
"sql",
""
] |
The existing design for this program is that all changes are written to a changelog table with a timestamp. In order to obtain the current state of an item's attribute we `JOIN` onto the changelog table and take the row having the most recent timestamp.
This is a messy way to keep track of current values, but we canno... | **Edit:** Started this answer before Richard Harrison answered, promise :)
I would suggest another table with the structure similar to below:
```
VersionID TableName UniqueVal LatestPrimaryKey
1 Orders 209 12548
2 Orders 210 12549
3 Orders 211 12605
4... | I've done this before by having a "MostRecentRecorded" table which simply has the most recently inserted record (Id and entity ID) fired off a trigger.
Having an extra column for this isn't right - and can get you into problems with transactions and reading existing entries.
In the first version of this it was a simp... | How should I reliably mark the most recent row in SQL Server table? | [
"",
"sql",
"triggers",
"sql-server-2008-r2",
""
] |
I understand that any join can be done with a CROSS join and a WHERE clause.
I did some experiments, and it looks like placing the equality predicate inside the where clause or as the parameter of an inner join yields the same result with the same performance.
Furthermore, using inner joins does not save any typing, ... | Not any join can be done with a CROSS join and a WHERE clause.Each of the join cross, inner and outer has it's own logical significance.
1. **A cross join applies only one phase—Cartesian Product.**
2. **An inner join applies two phases—Cartesian Product and Filter.**
3. **An outer join applies three phases—Cartesian ... | The answer is performance may not be impacted, however, readability and code clarity is hindered when you have experienced developers looking at cross joins when they are really inner joins. Other than that it is a matter of personal preference. | Are INNER JOIN and OUTER JOIN necessary? | [
"",
"sql",
"database",
"join",
""
] |
I have two almost identical tables A and B in a SQL Server database.
Table A contains data and a primary key X set to `Is Identity == No`.
Table B contains no data but has primary key X set to `Is Identity == Yes` (`Identity Increment = 1, Identity Seed = 1`).
The data in primary key X increments by 1 to 100 i.e tab... | You use `set identity_insert tableB on` before running your `insert`
```
set identity_insert tableB on
insert tableB (Id, field1, field2)
select id, field1, field2 from tablea
set identity_insert tableB off
``` | Yes, you need to enumerate the columns. On the other hand - is on the B table the identity necessary, while its taken from A?
> The data in primary key X increments by 1 to 100 i.e table A has 100 records, the first record is 1 and the 100th record is 100.
Following this rule seems the incrementation on B not being n... | Copying data into table A into table B (Is Identity == Yes) | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a sql table like :
```
id buy_product buy_product_total sell_product sell_product_total
1 apple 5
2 banana 8
3 cake 20
4 apple 1
5 ... | As others have noted, your table structure is less than optimal.
However, given what you have, this will give you the results you're after.
```
select product, sum(total) from
(
select buy_product as product, buy_product_total as total
from yourtable
where buy_product is not null
union
s... | Is not a good table, could be better that buy and sell to be the same collumn buy with positive values and sell with negative.
But answer your question, suppose that your table name is myTable,
obs: you can execute every select separeted to understand better
```
select buy_product as product_name, (buy_total - sell_t... | SQL Table Solution With Calculating Different Columns in Same Table | [
"",
"mysql",
"sql",
""
] |
According to another SO post ([SQL: How to keep rows order with DISTINCT?](https://stackoverflow.com/questions/7026234/sql-how-to-keep-rows-order-with-distinct)), distinct has pretty undefined behavior as far as sorting.
I have a query:
```
select col_1 from table order by col_2
```
This can return values like
```
... | This all has to do with the "logical ordering" of SQL statements. Although a DBMS might actually retrieve the data according to all sorts of clever strategies, it has to behave according to some predictable logic. As such, the different parts of an SQL query can be considered to be processed "before" or "after" one ano... | I would go for something like
```
select col1
from (
select col1,
rank () over(order by col2) pos
from table
)
group by col1
order by min(pos)
```
In the subquery I calculate the position, then in the main query I do a group by on col1, using the smallest position to order.
Here the [demo in SQLFiddle](http:/... | SQL select distinct but "keep first"? | [
"",
"mysql",
"sql",
""
] |
I have a DB called Johnson containing 50 tables. The team that uses this DB has asked if I can provide them with a size estimate for each table
How can I display a list of all the tables within the DB and their respective size in GB or MB using SQL Server? | ```
SET NOCOUNT ON
DBCC UPDATEUSAGE(0)
-- DB size.
EXEC sp_spaceused
-- Table row counts and sizes.
CREATE TABLE #t
(
[name] NVARCHAR(128),
[rows] CHAR(11),
reserved VARCHAR(18),
data VARCHAR(18),
index_size VARCHAR(18),
unused VARCHAR(18)
)
INSERT #t EXEC sp_msForEachTable 'EXEC sp_s... | You could use SSMS to display the size of biggest 1000 tables thus:
 | How to analyze tables for size in a single DB using SQL Server? | [
"",
"sql",
"sql-server",
""
] |
I am having trouble with a SQL Server query. I have a couple of tables involved `[Order]` (I know, not named well) and `[Order Entry]`.
Order Entry is basically a "Line Item" on an Order (so there are one or more per Order). There are various columns in Order Entry, one of which is `ItemID` (there is only one `ItemID`... | I was able to take a few pieces from several of you (Miguel Guzman - you provided the spark I needed to get this) and got it working. Here is my final Query:
```
SELECT o.ID, o.StoreID
FROM [Order] o
JOIN PSD_ServiceTicket st
ON o.ID = st.WorkOrderID
AND o.StoreID = st.StoreID
WHERE o.StoreID = 101
AND o.Time >= '... | If I'm understanding you correctly, you want something like this. Starting your query with the Orders table and using a left join will ensure that you get the orders you're looking for. By left joining with a match on ItemID, you can then check for nulls in your where statement to find the orders that don't have those ... | Selecting Orders with multiple line items but not when one or more line items contains a defined list | [
"",
"sql",
"sql-server",
"inner-join",
""
] |
I have tables:
```
Users{UserId ...}
Professors{UserId ...}
```
I set `UserId` to be PK in both tables and made 1:1 relationship.
But if I try to insert new user it doesn't work as it requires insert in the `Professor` table too.
I want to make that one user can have only 1 record in Professor table but I also want... | If you have these requirements:
* a User can be Professor - or not
* a Professor is always a User
then you are correct that it's a `1 :: 0..1` relationship. In SQL, it can be implemented like this:
```
CREATE TABLE Users
( UserId INT NOT NULL
, ...
, PRIMARY KEY (UserId)
) ;
CREATE TABLE Professors
( User... | I think you are should use foreign key here.
Professor ID should be the foreign key in the user table, that will solve all your problem.
Just look up what foreign key is and how to write foreign key query | How to set 1 to 0...1 relationship in SQL Server Management Studio | [
"",
"sql",
"database",
"database-design",
"relational-database",
"ssms",
""
] |
I am about to embark on a project for work that is very outside my normal scope of duties. As a SQL DBA, my initial inclination was to approach the project using a SQL database but the more I learn about NoSQL, the more I believe that it might be the better option. I was hoping that I could use this question to describ... | May as well make this an answer. I should comment that I'm not strong in NoSQL, so I tend to lean towards SQL.
I'd do this as a three table set. You will see it referred to as entity value pair logic on the web...it's a way of handling multiple dynamic attributes for items. Lets say you have a bunch of products and ea... | This problem can be solved in by using two separate pieces of technology. The first is to use a relatively well designed database schema with a modern RDBMS. By modeling the application using the usual principles of normalization, you'll get really good response out of storage for individual CRUD statements.
Searching... | SQL vs NoSQL for data that will be presented to a user after multiple filters have been added | [
"",
"sql",
"object",
"attributes",
"nosql",
"filtering",
""
] |
Basically I got a table in my EF database with the following properties:
```
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Image { get; set; }
public string WatchUrl { get; set; }
public int Year { get; set; }
public string Source { get; set; }
publ... | Try this:
Remove the constraint *DF\_Movies\_Rating\_\_48CFD27E* before changing your field type.
The constraint is typically created automatically by the DBMS (SQL Server).
To see the constraint associated with the table, expand the table attributes in **Object explorer**, followed by the category *Constraints* as ... | I'm adding this as a response to explain where the constraint comes from.
I tried to do it in the comments but it's hard to edit nicely there :-/
If you create (or alter) a table with a column that has default values it will create the constraint for you.
In your table for example it might be:
```
CREATE TABLE Movie... | The object 'DF__*' is dependent on column '*' - Changing int to double | [
"",
"sql",
"sql-server",
"database",
"entity-framework",
"entity-framework-4",
""
] |
I have the following two tables:
```
rsrpID rsrpName
1 Library Catalog
2 Interlibrary Loan
3 Academic Search Complete
4 JSTOR
5 Project Muse
6 LibGuides
7 Web Resource
8 Other (please add to Notes)
9 Credo Reference
rsriID rsrirsrpID rsrisesdID
603 6 ... | You are looking for an Outer Join:
```
select rp.rsrpID as ID, rp.rsrpName as Name, ri.rsrisesdID
from resourcepool rp
left outer join resourcesintroduced ri on (ri.rsrirsrpID = rp.rsrpID and ri.rsrisesdID = 243)
``` | You use a LEFT JOIN
```
SELECT
rsrpID,
rsrpName,
vrsrisesdID
FROM
rp LEFT JOIN
ri ON rp.rsrpID = ri.rsrirsrpID
```
Which returns:
```
1 Library Catalog 243
2 Interlibrary Loan NULL
3 Academic Search Complete NULL
4 JSTOR NULL
... | Return all rows from one table, and match with a subset of rows from another table? | [
"",
"sql",
"join",
""
] |
I have two tables:
table A: table B:
```
id m1 id m2
------ -------
1 a 1 a
2 b 2 c
3 3 d
```
when I execute the sql:
```
select A.*,B.id as mid from A left join B on A.m1 = b.m2
```
I want to get the result:
```
id m1 mid
-------------... | I'm getting the correct results in this [fiddle](http://sqlfiddle.com/#!2/986f44/1).
```
| ID | M1 | MID |
|----|--------|--------|
| 1 | a | 1 |
| 2 | b | (null) |
| 3 | (null) | (null) |
```
It will also work for empty strings. The resulting behaviour you're mentioning goes against the left... | NULL comparison results in unknown so you might want to replace NULL with something in JOIN condition. | Problems about 'left join' in MySQL | [
"",
"mysql",
"sql",
"left-join",
""
] |
I'm having some trouble figuring out a SQL Server query. The relational model is quite old (it seems) and is not very optimal, to say the least.
My query looks like this:
```
SELECT
[RequestUsers].requestId, [Requests].name, [Requests].isBooked
FROM
[RequestUsers]
JOIN
[Requests] ON [RequestUsers].requ... | ```
SELECT [RequestUsers].requestId,
[Requests].name,
[Requests].isBooked,
Count(*) AS requestCount
FROM [RequestUsers]
JOIN [Requests]
ON [RequestUsers].requestId = [Requests].id
WHERE [RequestUsers].dateRequested >= '10-01-2013'
AND [RequestUsers].dateRequested <= '1... | ```
SELECT [RequestUsers].requestId, [Requests].name, [Requests].isBooked,
COUNT([RequestUsers].requestId) "requestCount"
FROM [RequestUsers]
JOIN [Requests]
ON [RequestUsers].requestId = [RequestUsers].id
WHERE [RequestUsers].dateRequested >= '10-01-2013'
AND [RequestUsers].dateRequested <= '10-16-2013'
GROUP BY [Requ... | Count unique rows in SQL Server query | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
So I have data like this:
```
UserID CreateDate
1 10/20/2013 4:05
1 10/20/2013 4:10
1 10/21/2013 5:10
2 10/20/2012 4:03
```
I need to group by each user get the average time between CreateDates. My desired results would be like this:
```
UserID AvgTime(minutes)
1 753.5
2 0
```
... | Try this:
```
SELECT A.UserID,
AVG(CAST(DATEDIFF(MINUTE,B.CreateDate,A.CreateDate) AS FLOAT)) AvgTime
FROM #YourTable A
OUTER APPLY (SELECT TOP 1 *
FROM #YourTable
WHERE UserID = A.UserID
AND CreateDate < A.CreateDate
ORDER BY CreateDate DESC) B
GROUP BY A.U... | This approach should aslo work.
**[Fiddle demo here](http://sqlfiddle.com/#!6/84ba5/10)**:
```
;WITH CTE AS (
Select userId, createDate,
row_number() over (partition by userid order by createdate) rn
from Table1
)
select t1.userid,
isnull(avg(datediff(second, t1.createdate, t2.createdate)*... | Get average time between record creation | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2012",
""
] |
I am doing my project in MVC4 using c# and sql.. I have a table `MemberDetails` which contain table
```
CREATE TABLE [dbo].[MemberDetails] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Mem_FirstNA] VARCHAR (100) NOT NULL,
[Mem_LastNA] VARCHAR (100) NOT NULL,
[Mem_Occ] VARCHAR (100) NOT NULL,
[Mem_DOB] ... | Try this...
~~SELECT
Mem\_FirstNA, Mem\_LastNA, Mem\_DOB
FROM
MemberDetails
WHERE
ltrim(str(year(GETDATE()))) + '-' + ltrim(str(month(Mem\_DOB))) + '-' + ltrim(str(day(Mem\_DOB))) >= getdate() - 1 AND ltrim(str(year(GETDATE()))) + '-' + ltrim(str(month(Mem\_DOB))) + '-' + ltrim(str(day(Mem\_DOB))) <= getdate() + 30~~
... | Updated
```
SELECT
Mem_FirstNA, Mem_LastNA, Mem_DOB
FROM
MemberDetails
WHERE
DATEDIFF(DAY, GETDATE(), DATEADD(YEAR, DATEDIFF(YEAR, Mem_DOB, GETDATE()), Mem_DOB)) BETWEEN 0 AND 30
``` | How to get 30 days from now from SQL table | [
"",
"sql",
"sql-server-2008",
""
] |
I have in my database (SQL Server 2008 R2) a table like this:
```
ID......Team...........Name......Age
102 Barcelona Mike 15
103 Barcelona Peter 10
104 Barcelona Jacke 10
105 Barcelona Jonas 10
106 Real Madrid Michael 20
107 Real Madrid Terry ... | If I understood your question correctly it looks like what you want are aggregates for each group, something that is easily accomplished with the [GROUP BY](http://technet.microsoft.com/en-us/library/ms177673.aspx) clause.
For the first query you would use:
```
SELECT team, SUM(age) AS 'Sum of the team'
FROM table
... | ```
SELECT TEAM , Name, COUNT(TEAM) As GoalsPerTeam, COUNT(NAME) As GoalPerPlayer
FROM TABLE
GROUP BY TEAM , Name
```
This query will give you tolal goals scored by per player and per team . | Calculate in a table with different cells - SQL Server / T-SQL | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
""
] |
How do I make MySQL's SELECT DISTINCT case sensitive?
```
create temporary table X (name varchar(50) NULL);
insert into X values ('this'), ('This');
```
Now this query:
```
select distinct(name) from X;
```
Results in:
> this
What's going on here? I'd like SELECT DISTINCT to be case sensitive. Shouldn't that be t... | Use [`BINARY` operator](http://dev.mysql.com/doc/refman/5.0/en/charset-binary-op.html) for that:
```
SELECT DISTINCT(BINARY name) AS Name FROM X;
```
You can also [`CAST`](https://dev.mysql.com/doc/refman/5.7/en/cast-functions.html#function_cast) it while selecting:
```
SELECT DISTINCT
(CAST(name AS CHAR CHARACTER ... | I would rather update the column definition to be case sensitive collision.
Like this:
```
create table X (name VARCHAR(128) CHARACTER SET utf8 COLLATE utf8_bin NULL);
insert into X values ('this'), ('This');
```
SQLFiddle: <http://sqlfiddle.com/#!2/add276/2/0> | MySQL SELECT DISTINCT should be case sensitive? | [
"",
"mysql",
"sql",
"distinct",
"case-sensitive",
""
] |
How can I select all BUT the last row in a table?
I know I can select the last via `SELECT item FROM table ORDER BY id DESC LIMIT 1` but I want to select ALL but the last.
How can I do this?
Selecting a certain amount and using `ASC` won't work because I won't know how many rows there are.
I thought about doing a r... | If Id is unique, you can do it as follows:
```
SELECT ...
FROM MyTable
WHERE Id < (SELECT MAX(Id) FROM MyTable)
``` | The easiest way to do this is to discard the row in the application. You can do it in SQL by using a calculated limit. Calculate it as `(SELECT COUNT(*) FROM T) - 1`.
Or:
```
SELECT *
FROM T
EXCEPT
SELECT TOP 1 *
FROM T
ORDER BY id ASC
```
Excluding the last row. | SQL Selecting all BUT the last row in a table? | [
"",
"sql",
""
] |
Trying to search in a database a date range. Problem is, I cannot use the datetime column type in my database. To compensate, date's are displayed as three columns. a Month column, a Day column, and a Year column. Here is my SQL query:
```
SELECT COUNT(*)
FROM `import`
WHERE `call_day` BETWEEN 29 AND 15
AND `... | Besides the concatenation approach, which can be implemented in quite a few ways, e.g.
```
SELECT *
FROM import
WHERE STR_TO_DATE(CONCAT_WS('-', call_year, call_month, call_day), '%Y-%c-%e')
BETWEEN '2013-09-29' AND '2013-10-15'
```
or
```
SELECT *
FROM import
WHERE CONCAT(call_year, LPAD(call_month, ... | Concat the values like yyyymmdd and then you can compare them like strings. | SQL search between two days without datetime | [
"",
"mysql",
"sql",
"datetime",
""
] |
I'm still starting to put my feet into SQL. I have a problem with querying dates and group them. I want to group the dates. And from this dates display the name, type of visit on a specific range of dates.
Say from the example below, I want to query the people who visited from the the range of **01/01/2012 until 31/12... | ```
SELECT DISTINCT NAME
FROM YOUR_tABLE
WHERE (TYPE_OF_VISIT = 4) AND (DATE_OF_VISIT BETWEEN ? AND ?)
```
if you want the first visit of each customer within this range, then you should try sth like this
```
SELECT DISTINCT T1.NAME, T1.DATE_OF_VISIT
FROM YOUR_TABLE T1
WHERE (T1.TYPE_OF_VISIT = 4) AND (T1.DATE_OF_... | If column Date\_of\_visit does not contain any time portion (ie. only date). You can execute the following
```
SELECT NAME, TYPE_OF_VISIT
FROM appointment
WHERE Type_of_visit = 4
AND Date_of_visit >= '01/01/2012 '
AND Date_of_visit <= '31/12/2012'
GROUP BY NAME
``` | Query relating to multiple Dates | [
"",
"sql",
"date",
"grouping",
""
] |
for an assignment I had something similar to the following (simplified for brevity):
```
STUDENT(StudentID, Fname. Lname) StudentID PK
UNIT(UnitID, UnitName) UnitID PK
STUDENT_UNIT((StudentID, UnitID) StudentID PK/FK UnitID PK/FK
```
Needed to insert info about a student and the units that he/she had com... | One of the best approach to do this is by using `stored procedure`. The below procedure will do everything for you.
```
CREATE OR REPLACE
PROCEDURE set_stud_unit(
i_fname IN VARCHAR2,
i_lname IN VARCHAR2,
i_unitid IN VARCHAR2)
IS
l_studentid student.studentid%TYPE;
BEGIN
INSER... | you can use select in your insert:
```
INSERT INTO STUDENT_UNIT select t1.StudentID ,t2.UnitID from STUDENT t1 ,UNIT t2;
```
and you can use where to limit this selection ;-) | Oracle SQL insert query - into parent and child tables | [
"",
"sql",
"oracle",
"insert",
""
] |
Here am having Person and Address Tables .Some Persons may have address or not.If they have address then want to join address table otherwise no need to join.Please help to solve this case.
```
select p.name,nvl(a.address,'address not available') from person p,address a
where p.id = 2 and case
when p.addid... | The *general solution* - use Boolean logic. You cannot choose between complete expressions using CASE, so you should rewrite it to use a combination of AND and OR. Using the logic from your question, you would rewrite it as:
```
WHERE p.id = 2
AND
(
(p.addid IS NOT NULL AND p.addid = a.id)
OR (p.addid IS NULL... | Try to use **coalesce** function as below
```
select p.name,nvl(a.address,'address not available') from person p,address a
where p.id = 2
and coalesce(p.addid,a.id)=a.id
``` | How to compare with Case in Where clause | [
"",
"sql",
"oracle",
""
] |
In sql table i have fields: *name*, *description* and *language*
my language field has values like: "en-GB" or "fr-FR".
```
SELECT * FROM items WHERE `name` LIKE '%yellow%' OR `description` LIKE '%yellow%' AND `language` = 'en-GB';
```
Results with search term **yellow** are ok. but i get also results who has langau... | Use paranthesis
```
SELECT * FROM items
WHERE (`name` LIKE '%yellow%' OR `description` LIKE '%yellow%') AND `language` = 'en-GB';
``` | You need to use brackets as the 'OR' operated is evaluated first, where you are expecting the 'AND' operator to be.
```
SELECT *
FROM items
WHERE (`name` LIKE '%yellow%' OR `description` LIKE '%yellow%')
AND `language` = 'en-GB'
``` | SQL request - search query not working | [
"",
"sql",
"search",
""
] |
I have following table as LocalBarcode:

and following as Barcodecancel cancel :
I want to take:
1. count of total barcodes
2. count of barcodes whose IsUpload is true
from LocalB... | ```
select (select count(barcode)
from localbarcode
where Int([TimeStamp])= Format(CDate('10/18/2013'))),
(select count(isupload)
from localbarcode
where isupload=0),
(select count(barcode)
... | You can get required output using following query:
select count(LocalBarcode.Barcode), count(lb.Barcode), count(lb1.Barcode) from LocalBarcode left join LocalBarcode lb on LocalBarcode.Barcode = lb.Barcode and LocalBarcode.IsUpload = 1 left join Barcodecancel lb1 on LocalBarcode.Barcode = lb1.Barcode and LocalBarcode.... | taking data from multiple tables in single query | [
"",
"mysql",
"sql",
"database",
"oledb",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.