Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
In ms sql database table files\_master I have a column named 'AstNum' `varchar(100)` it contain data like:`1/1980
2/1980
11/1980`And so on when I sort the column:
```
SELECT AstNum FROM Files_master ORDER BY AstNum ASC
```
It shows me the records `1/1980,11/1980` in the column. `/1980` is the year before slash is inc... | Try this
```
Select AstNum from Files_master Order by convert(datetime,'1/'+AstNum,101) ASC
```
EDIT : Based on the comments, here is another solution
```
Select AstNum from Files_master
Order by
parsename(replace(AstNum,'/','.'),2)*1 ASC,parsename(replace(AstNum,'/','.'),1)*1 ASC
``` | This will easily not work that way, and probably also violates [standard database rules](https://en.wikipedia.org/wiki/Database_normalization).
Your way to go would be to have two columns, both of type `int`, with one of them being the index and the other the year. Say, you have columns `id` and `year`, your request w... | Sort by varchar column | [
"",
"sql",
"sql-server",
"sorting",
"sql-server-2014",
"varchar",
""
] |
I have the following table
```
Id, Class1, Class2, Class3
1 1 2 3
2 2 3 3
3 1 2 3
```
When exact duplicate rows (Class1,Class2,Class3) appear apart from the primary key I want to take the first record found and ignore further records with that same fields.
So
I want th... | you can use the following:
```
select * from t1 where ID in(select min(Id) FROM t1 group by Class1, Class2, Class3)
```
Example Demo:
<http://sqlfiddle.com/#!3/88fab> | ```
with cte
as
(select *,
row_number() over (partition by class1,class2,class3 order by id ) as rn from #temp
)
select * from cte where rn=1
``` | How to in SQL return first found primary key for criteria that has duplicates | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a table representing a system of folders and sub-folders with an ordinal `m_order` column.
Sometimes sub-folders are sorted alphanumerically, others are sorted by date or by importance.
I recently had to delete some sub-folders of a particular parent folder and add a few new ones. I also had to switch the orde... | I would do this with a simple `update`:
```
with toupdate as (
select m.*, row_number() over (partition by parent order by title) as seqnum
from menu m
)
update toupdate
set m_order = toupdate.seqnum;
```
This restarts the ordering for each parent. If you have a particular parent in mind, use a `... | After deleting the old folders and inserting the new records, I accomplished the reordering by using `MERGE INTO` and `ROW_NUMBER()`:
```
DECLARE @parentID INT
...
MERGE INTO menu
USING (
SELECT ROW_NUMBER() OVER (ORDER BY title) AS rowNumber, ID
FROM menu
WHERE parent = @parentID
) AS r... | Update an ordinal column based on the alphabetic ordering of another column | [
"",
"sql",
""
] |
i'm a newbie in SQL. I have 2 tables
Table 1 (TBMember):
```
MemberCode | Date
001 | Jan 21
002 | Jan 21
003 | Jan 21
004 | Jan 21
```
Table 2 (TBDeposit):
```
Date | MemberCode | Deposit
Jan 21 | 001 | $100
Jan 21 | 001 | $200
Jan 21 | 002 | $300
Jan 21 | 002 | $400
Jan 21 | 003 | $50... | @Darren: Ankit Bajpai answer is right. Please try with sample data that you provided below.
```
--Data Setup
Declare @TBMember table(MemberCode varchar(3), MDate varchar(20))
insert into @TBMember
values
('001','Jan 21'),
('002','Jan 21'),
('003','Jan 21'),
('004','Jan 21')
--Table 2 (TBDeposit):
Declare @TBDeposit t... | try this:
```
select count(distinct dp.MemberCode)
from TBDeposit dp
inner join TBMember mmb
on dp.MemberCode = mmb. MemberCode and dp.Date = mmb.Date
```
if you want to limit the date to some specific date you just go with where Date = 'date you want to known' | How To Find A Member That Register And Deposit At The Same Day | [
"",
"sql",
"sql-server",
"database",
""
] |
Here is what I tried:
```
SELECT SUM(PQ.QuotaValue)
FROM PackageQuotas AS PQ
JOIN (
SELECT DISTINCT PackageID,
ParentPackageID
FROM Packages
WHERE ParentPackageID = @ParentPackageID
) PA ON PQ.PackageID = PA.PackageID
WHERE PQ.QuotaID = @QuotaID
```
The common column is the ParentPacka... | ```
CREATE /* UNIQUE */ INDEX ix ON dbo.PackageQuotas (QuotaID, PackageID)
INCLUDE (QuotaValue)
WHERE QuotaValue > 0
SELECT SUM(q.QuotaValue)
FROM dbo.PackageQuotas q /* WITH(INDEX(ix)) */
WHERE q.QuotaID = @QuotaID
AND q.QuotaValue > 0
AND EXISTS(
SELECT 1
FROM dbo.Packages p
... | Remove the null and Negative values by adding condition in Where Clause
```
SELECT SUM(PQ.QuotaValue)
FROM PackageQuotas AS PQ
JOIN (
SELECT DISTINCT PackageID,
ParentPackageID
FROM Packages
WHERE ParentPackageID = @ParentPackageID
) PA ON PQ.PackageID = PA.... | How to sum the values of one colum except negative numbers or null in SQL | [
"",
"sql",
"sql-server",
""
] |
I'm trying to pull in data from several tables, one of which has a one-to-many relationship. My SQL looks like this:
```
SELECT
VU.*,
UI.UserImg,
COALESCE(CI.Interests, 0) as NumInterests
FROM [vw_tmpUsers] VU
LEFT JOIN (
SELECT
[tmpUserPhotos].UserID,
CASE WHEN MAX([tmpUserPhotos].uFileName) = ... | You need to check for `NULL` in the outer query:
```
SELECT VU.*,
COALESCE(UI.UserImg, 'dflt.jpg') as UserImg,
COALESCE(CI.Interests, 0) as NumInterests
FROM [vw_tmpUsers] VU LEFT JOIN
(SELECT [tmpUserPhotos].UserID, MAX([tmpUserPhotos].uFileName) as UserImg
FROM [tmpUserPhotos]
GROU... | Instead of the case statement, try the 'isnull' function...
```
isnull(MAX([tmpUserPhotos].uFileName),'dflt.jpg') as UserImg
``` | Trouble with a JOIN | [
"",
"sql",
"sql-server-2008-r2",
""
] |
I am trying to design a database schema for the following entities: Stores, Products, Discounts and Buyers. The goal is to provide a discount campaign for a couple of products. However, on my first iteration over the database schema I can see there is a circular dependency as illustrated bellow:
[
Or:
[](https://i.stack.imgur.com/Cyurx.png) | SQL Circular Dependency | [
"",
"mysql",
"sql",
"database",
"database-design",
""
] |
I have a stored procedure that returns columns . This stored procedure is mainly being used by other query for functional reasons
So my stored procedure:
```
IF OBJECT_ID ( 'dbo.ProcDim', 'P' ) IS NOT NULL
DROP PROCEDURE dbo.ProcDim;
GO
CREATE PROCEDURE dbo.ProcDim
@Dim1 nvarchar(50),... | You can't use temporary table in such a manner.
By this code: `SELECT INTO #TMP1` you're implicity creating temporary table, and it is accessible in the scope of your stored procedure - but not outside of this scope.
If you need this temporary table to be accessible outside of stored procedure, you have to remove `IN... | Temp tables are scoped (in this case) to the stored procedure in which they're created. That is, when your stored procedure completes, the temp table is dropped.
If you need the contents of the temp table, select from it *before* the end of the procedure - IOW, `select * from #TMP1` should be the output of the procedu... | Can't store procedure into dynamic temp table | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
""
] |
I have an Syntax error in my SQL create table command but cant understand why?
```
CREATE TABLE E0 (
div VARCHAR(50),
date VARCHAR(50), hometeam VARCHAR(50), awayteam VARCHAR(50),
fthg VARCHAR(50), ftag VARCHAR(50), ftr VARCHAR(50),
hthg VARCHAR(50), htag VARCHAR(50), htr VARCHAR(50),
referee VARCH... | `as`, `div` and `date` are sql reserved words (see [manual](https://dev.mysql.com/doc/refman/5.7/en/keywords.html)), you cannot have such names without escaping with backticks. | One of the columns is named AS which is a reserved word. Either use different name or wrap around `` like `as` varchar(50) | Syntax error in SQL create table command | [
"",
"mysql",
"sql",
""
] |
I'm having trouble understanding other questions I see, as they are a little bit different.
I'm getting a XML as response from a webservice vi UTL\_HTTP. The XML has repeating child nodes and I want to extract only 1 specific value.
The response XML:
```
<Customer>
<Loyalty>
<Client>
<Identifica... | Aaand I managed to find the solution, which is quite simple, just added [text()="Form3"]/.../" to predicate the Xpath as in
```
SELECT
ExtractValue(Value(p),'/Customer/Loyalty/Client/Identifications/Identification/*[local-name()="Form"][text()="Form3"]/text()') as form,
ExtractValue(Value(p),'/Customer/Loya... | with this sql you should get the desired value:
```
with data as
(select '<Customer>
<Loyalty>
<Client>
<Identifications>
<Identification>
<Form>Form1</Form>
<value>1234</value>
</Identification>
<Identification>
<Form>Form2</Form>... | XML Oracle: Extract specific attribute from multiple repeating child nodes | [
"",
"sql",
"xml",
"oracle",
"plsql",
""
] |
I have written an SQL script which runs fine when executed directly in SQL Management Studio. However, when entering it into Power BI as a source, it reports that it has an incorrect syntax.
This is the query:
```
EXEC "dbo"."p_get_bank_balance" '2'
```
However, the syntax is apparently incorrect? See Pi... | I found time ago the same problem online on power bi site:
<http://community.powerbi.com/t5/Desktop/Use-SQL-Store-Procedure-in-Power-BI/td-p/20269>
> You must be using DirectQuery mode, in which you cannot connect to data with stored procedures. Try again using Import mode or just use a SELECT statement directly. | In DirectQuery mode, PowerBI automatically wraps your query like so: `select * from ( [your query] )`, and if you attempt this in SSMS with a stored procedure i.e.
```
select * from (exec dbo.getData)
```
You get the error you see above.
The solution is you have to place your stored procedure call in an OPENQUERY ca... | SQL reporting invalid syntax when run in Power BI | [
"",
"sql",
"sql-server",
"powerbi",
""
] |
Basically, I've got the following table:
```
ID | Amount
AA | 10
AA | 20
BB | 30
BB | 40
CC | 10
CC | 50
DD | 20
DD | 60
EE | 30
EE | 70
```
I need to get unique entries in each column as in following example:
```
ID | Amount
AA | 10
BB | 30
CC | 50
DD | 60
EE | 70
```
So far following snippet gives almost what I w... | This works for me, even with the problematic combinations mentioned by Dimitri. I don't know how fast that is for larger volumes though
```
with ids as (
select id, row_number() over (order by id) as rn
from data
group by id
), amounts as (
select amount, row_number() over (order by amount) as rn
from data
... | My solution implements recursive `with` and makes following: first - select minival values of `ID` and `amount`, then for every next level searches values of `ID` and `amount`, which are more than already choosed (this provides uniqueness), and at the end query selects 1 row for every value of recursion level. But this... | How can I select unique values from several columns in Oracle SQL? | [
"",
"sql",
"oracle",
""
] |
Following is a simple table with only two columns `patientid` (id of a patient) and `visitdate` (date when patient visited the clinic) in SQL Server.
Each row represents a patient visit. Created a table variable and inserted some dummy data for testing purpose below. Attempted to write a query that display the days si... | This query is simpler and perform better based on provided sample data
Per execution plan, it is 4 times faster.
```
;with cte as (
select patientid, visitdate, (select max(visitdate) from @patientvisits
where patientid = p.patientid and visitdate < p.visitdate) prevVisitDate
from @patientvisits p
)
select patientid... | `CROSS JOIN` plus join-condition in `WHERE` is the same as an Inner Join. Why do you cast the number of days as a `VarChar(10)`?
There's no need for UNION or repeating the same Select multiple times:
```
WITH cte as
(
SELECT row_number() over (partition by patientid order by visitdate desc) rowid, patientid, vi... | SQL Server : query to displays days since last visit. Can optimize this and/or use in-built SQL function to avoid self join and simply the query | [
"",
"sql",
"sql-server",
"performance",
"sql-server-2008-r2",
""
] |
Using VBScript, I create a recordset from a SQL query through and ADO connection object. I need to be able to write the field names and the largest field length to a text file, essentially as a two dimensional array, in the format of FieldName|FieldLength with a carriage return delimiter, example:
Matter Number|x(13) ... | After a little more research and testing I solved the issue by creating a dictionary based on the recordset field (column) count, then iterating through each item and evaluating the length of each field:
Dim Connection
Dim Recordset
```
Set Connection = CreateObject("ADODB.Connection")
Set Recordset = CreateObject("A... | If I understand the question correctly (I'm not certain I do)....
If you change your SQL statement you only need to return one record.
```
Select Max(Len([Matter Number])) as [Matter Number],
Max(Len([Description])) As Description, Max(Len([Due Date])) As [Due Date] FROM TableName
```
This will return the maximu... | VBScript Recordset Field Names and Length | [
"",
"sql",
"vbscript",
""
] |
I have a table: tblperson
There are three columns in tblperson
```
id amort_date total_amort
C000000004 12/30/2015 4584.00
C000000004 01/31/2016 4584.00
C000000004 02/28/2016 4584.00
```
The user will have to provide a billing date `@bill_date`
I want to sum all t... | You would use aggregation and inequalities:
```
select id, sum(total_amort)
from webloan.dbo.amort_guide
where loan_no = 'C000000004' and
year(amort_date) * 12 + month(amort_date) <= @year * 12 + @month
group by id;
```
Alternatively, in SQL Server 2012+, you can just use `EOMONTH()`:
```
select id, sum(total_... | You can get the start of the month using:
```
DATEADD(MONTH, DATEDIFF(MONTH, 0, @bill_date), 0)
```
So to get the `SUM(total_amort)`, your query should be:
```
SELECT
id,
SUM(total_amort) AS sum_total_amort
FROM webloan.dbo.amort_guide
WHERE
loan_no='C000000004'
AND amort_date < DATEADD(MONTH, DATE... | Query all dates less than the given date (Month and Year) | [
"",
"sql",
"sql-server",
""
] |
I am trying to write a select statement gathering one row for each name. Expected output is hence:
Name=Al, Salary=30, Bonus=10
Table\_1
```
Name Salary
Al 10
Al 20
```
Table\_2
```
Name Bonus
Al 5
Al 5
```
How do I write that?
I try to:
```
Select t1.Name, SUM(t1.Salary), SUM(t2.Bonus) FROM tab... | Group the tables separately by employee, then join them:
```
SELECT t1.Name, Salary, Bonus
FROM (
SELECT Name, SUM(Salary) Salary
FROM table_1
GROUP BY Name
) t1
LEFT JOIN (
SELECT Name, SUM(Bonus) Bonus
FROM table_2
GROUP BY Name
) t2 ON t1.Name = t2.Name
``` | You can do it with a subquery like this:
```
declare @salary table (Name varchar(100), value int)
declare @bonus table (Name varchar(100), value int)
insert into @salary
values ('al', 10)
insert into @salary
values ('al', 20)
insert into @bonus
values ('al', 5)
insert into @bonus
values ('al', 5)
select s.Name, ... | Join gives incorrect sum | [
"",
"sql",
"teradata",
""
] |
I am new in mysql. What I would to do is create a new table which is a copy of the original one *table* with one more column under a specific condition. Which condition appears as a new column is the new table. I mean:
Let *table* be a sequence of given point (x,y) I want to create the table *temp* being (x,y,r) where... | You don't actually need to worry about doing the calculation twice. There is more overhead to doing an `insert` and `update`. So, you should do those calculations at the same time.
MySQL extends the use of the `having` clause, so this is easy:
```
CREATE temp LIKE table;
ALTER TABLE temp ADD r FLOAT;
INSERT INTO tem... | You should (almost) never store calculated data in a database. It ends up creating maintenance and application nightmares when the calculated values end up out of sync with the values from which they are calculated.
At this point you're probably saying to yourself, "Well, I'll do a really good job keeping them in sync... | MySQL CLAUSE can become a value? | [
"",
"mysql",
"sql",
"database",
"optimization",
""
] |
There's already an answer for this question in SO with a MySQL tag. So I just decided to make your lives easier and put the answer below for SQL Server users. Always happy to see different answers perhaps with a better performance.
Happy coding! | ```
SELECT SUBSTRING(@YourString, 1, LEN(@YourString) - CHARINDEX(' ', REVERSE(@YourString)))
```
Edit: Make sure `@YourString` is trimmed first as Alex M has pointed out:
```
SET @YourString = LTRIM(RTRIM(@YourString))
``` | Just an addition to answers.
The doc for `LEN` function in MSSQL:
> LEN excludes trailing blanks. If that is a problem, consider using the DATALENGTH (Transact-SQL) function which does not trim the string. If processing a unicode string, DATALENGTH will return twice the number of characters.
The problem with the ans... | SQL Server query to remove the last word from a string | [
"",
"sql",
"sql-server",
""
] |
How can I select count(\*) from two different tables (table1 and table2) having as result:
```
Count_1 Count_2
123 456
```
I've tried this:
```
select count(*) as Count_1 from table1
UNION select count(*) as Count_2 from table2;
```
But here's what I get:
```
Count_1
123
456
```
I can see a solution for ... | Cross join two subqueries which return the separate counts:
```
SELECT sub1.Count_1, sub2.Count_2
FROM
(SELECT Count(*) AS Count_1 FROM table1) AS sub1,
(SELECT Count(*) AS Count_2 FROM table2) AS sub2;
``` | ```
Select TOP 1
(Select count(*) as Count from table1) as count_1,
(select count(*) as Count from table2) as count_2
From table1
``` | Select count(*) from multiple tables in MS Access | [
"",
"sql",
"ms-access",
""
] |
I need to populate a currency value column with a value which is calculated from 2 other columns.
So:
```
original_value amount new_value
12 2 NULL
10 1 NULL
```
This would become:
```
original_value amount new_value
12 ... | Just use `UPDATE`
```
UPDATE table_name
SET new_value = (original_value * amount)
WHERE new_value IS NULL
``` | As I said in my comment; *don't store computed values (from other columns.) Redundancy, not normalized, risk of data inconsistency! Create a view instead - will always be up to date!*
```
create view viewname as
select original_value, amount, original_value * amount as new_value
from tablename
```
SQL Server has comp... | populate null columns in database | [
"",
"mysql",
"sql",
"sql-server",
""
] |
What is an efficient way to get all records with a datetime column whose value falls somewhere between yesterday at `00:00:00` and yesterday at `23:59:59`?
SQL:
```
CREATE TABLE `mytable` (
`id` BIGINT,
`created_at` DATETIME
);
INSERT INTO `mytable` (`id`, `created_at`) VALUES
(1, '2016-01-18 14:28:59'),
(2,... | Since you're only looking for the date portion, you can compare those easily using [MySQL's `DATE()` function](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date).
```
SELECT * FROM table WHERE DATE(created_at) = DATE(NOW() - INTERVAL 1 DAY);
```
Note that if you have a very large numbe... | You can still use the index if you say
```
SELECT * FROM TABLE
WHERE CREATED_AT >= CURDATE() - INTERVAL 1 DAY
AND CREATED_AT < CURDATE();
``` | All MySQL records from yesterday | [
"",
"mysql",
"sql",
"datetime",
""
] |
I've got this TSQL:
```
CREATE TABLE #TEMPCOMBINED(
DESCRIPTION VARCHAR(200),
WEEK1USAGE DECIMAL(18,2),
WEEK2USAGE DECIMAL(18,2),
USAGEVARIANCE AS WEEK2USAGE - WEEK1USAGE,
WEEK1PRICE DECIMAL(18,2),
WEEK2PRICE DECIMAL(18,2),
PRICEVARIANCE AS WEEK2PRICE - WEEK1PRICE,
PRICEVARIANCEPERCENTAGE AS (WEEK2PRIC... | Try explicitly casting the computed column when you create the table, as below:
```
CREATE TABLE #TEMPCOMBINED(
DESCRIPTION VARCHAR(200),
WEEK1USAGE DECIMAL(18,2),
WEEK2USAGE DECIMAL(18,2),
USAGEVARIANCE AS WEEK2USAGE - WEEK1USAGE,
WEEK1PRICE DECIMAL(18,2),
WEEK2PRICE DECIMAL(18,2),
PRICEVARIANCE AS WEEK... | use ROUND function
```
SELECT ROUND(column_name,decimals) FROM table_name;
``` | How can I get my calculated SQL Server percentage value to only display two decimals? | [
"",
"sql",
"t-sql",
"precision",
"decimal-precision",
""
] |
I'm trying to find instances where a user has entered a person with their name backwards and then entered the person again correctly.
```
FirstName LastName
----------------------
Doc Jones
Jones Doc
Doc Holiday
John Doe
```
I want to get
```
Doc Jones
Jones Doc
```
I tried
```
... | Just for the sake of completeness. You can also use `INTERSECT`:
```
Select FirstName, LastName
From People
INTERSECT
Select LastName, FirstName
From People
```
This will return only one pair of matching rows, i.e.:
```
+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| Doc | Jones ... | ```
SELECT P1.FirstName, P1.LastName
FROM People P1
JOIN People P2
ON P1.FirstName = P2.LastName
AND P2.FirstName = P1.LastName
```
The problem I see is you dont have some form of ID you wont have a way to see what are the rows duplicated between lot of duplicates.
So maybe this is better
```
SELECT P1.*, ... | Find rows where the value in column 1 exists in colunm2 | [
"",
"sql",
"sql-server",
""
] |
I heard people saying that table joins can be used everywhere to replace sub-queries. I tested it in my query, but found that appropriate data set was only retrieved when I used sub-queries. I was not able to get same data set using joins. I am not sure if what I found is right because I am a newcomer in RDBMS, thus no... | For `not in` you can use `left join` and check for `is null`:
```
select u.id, u.name
from Users u
left join Friends f on u.id = f.id and f.friend_id = @person
where u.city like '%city%' and f.friend_id is null and u.id <> @person;
```
There are some cases where you can't work out your way with just inner/left/rig... | You can rewrite your query using only joins. The trick is to join to the User tables once with an inner join to identify users within the same city and reference the Friendship table with a left join and a null check to identify non-friends.
```
SELECT
U1.ID,
U1.Name
FROM
USERS U1
INNER JOIN
USERS U2... | Is it true that JOINS can be used everywhere to replace Subqueries in SQL | [
"",
"sql",
"join",
""
] |
So, I'm new to rails so this is probably a newbie question, but I didn't find any help for this problem anywhere...
Let's say I have a database containing "stories" here. The only column are the title and a timestamp :
```
create_table :stories
add_column :stories, :title, :string
add_column :stories, :date... | Without having to recreate the table from scratch, in terminal run 'rails g migration add\_timestamps\_to\_stories'
- find the newly created migration file, make sure it has the following:
```
def change
add_timestamps :stories
end
```
Run rake db:migrate
This adds two new columns, created\_at and updated\_at, you... | If you only want to track the creation timestamp of your story records, you could do it like this in your migration:
```
create_table do |t|
t.string :title
t.timestamps
end
```
In addition to your title field, this would create "created\_at" and "updated\_at" fields which are handled by ActiveRecord for you, lik... | Save date in database with rails | [
"",
"sql",
"ruby-on-rails",
"ruby",
""
] |
I am getting `Syntax error near 'ORDER'` from the following query:
```
SELECT i.ItemID, i.Description, v.VendorItemID
FROM Items i
JOIN ItemVendors v ON
v.RecordID = (
SELECT TOP 1 RecordID
FROM ItemVendors iv
WHERE
iv.VendorID = i.VendorID A... | I'd use max instead of top 1 ... order by
SELECT i.ItemID, i.Description, v.VendorItemID
FROM Items i
JOIN ItemVendors v ON
v.RecordID = (
SELECT max(RecordID)
FROM ItemVendors iv
WHERE
iv.VendorID = i.VendorID AND
iv.ParentRecordID = i.RecordID); | This error has nothing to do with TOP.
ASE simply does not allow ORDER BY in a subquery. That's the reason for the error. | SQL error on ORDER BY in subquery (TOP is used) | [
"",
"sql",
"sybase-asa",
""
] |
I've a question about the use of recursive SQL in which I have following table structure
Products can be in multiple groups (for the sake of clarity, I am not using int )
```
CREATE TABLE ProductGroups(ProductName nvarchar(50), GroupName nvarchar(50))
INSERT INTO ProductGroups(ProductName, GroupName) values
('Produ... | I don't think this is possible with a recursive CTE, because you're only allowed one recursive reference per recursive definition.
I did manage to implement it with a `while` loop, which is likely to be less efficient than the cte:
```
declare @related table (ProductName nvarchar(50), GroupName nvarchar(50))
-- base... | It can be done with a recursive query, but it's not optimal because SQL Server does not allow you to reference the recursive table as a set. So you end up having to keep a path string to avoid infinite loops. If you use ints you can replace the path string with a `hierarchyid`.
```
with r as (
select ProductName R... | Implementing a recursive query in SQL | [
"",
"sql",
"sql-server",
"recursive-query",
""
] |
I have been asked this in many interviews:
> What is the first step to do if somebody complains that a query is running slowly?
I say that I run `sp_who2 <active>` and check the queries running to see which one is taking the most resources and if there is any locking, blocking or deadlocks going on.
Can somebody ple... | This is one of my interview questions that I've given for years. Keep in mind that I do not use it as a yes/no, I use it to gauge how deep their SQL Server knowledge goes and whether they're server or code focused.
Your answer went towards how to find which query is running slow, and possibly examine server resource r... | I can't really say which is the best answer, but I'd answer: analyze the [Actual Execution Plan](https://learn.microsoft.com/en-us/sql/relational-databases/performance/display-an-actual-execution-plan). That should be a basis to check for performance issues.
There is plenty of information to be found on the internet a... | Fixing a slow running SQL query | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I need to improve my view performance, right now the SQL that makes the view is:
```
select tr.account_number , tr.actual_collection_trx_date ,s.customer_key
from fct_collections_trx tr,
stg_scd_customers_key s
where tr.account_number = s.account_number
and trunc(tr.actual_collection_trx_date) between s.s... | First, write the query using explicit `join` syntax:
```
select tr.account_number , tr.actual_collection_trx_date ,s.customer_key
from fct_collections_trx tr join
stg_scd_customers_key s
on tr.account_number = s.account_number and
trunc(tr.actual_collection_trx_date) between s.start_date and s.end_da... | If the start and end dates have no time elements (ie. they both default to midnight), then you could do:
```
select tr.account_number , tr.actual_collection_trx_date ,s.customer_key
from fct_collections_trx tr,
stg_scd_customers_key s
where tr.account_number = s.account_number
and tr.actual_collection_trx... | Improve view performance | [
"",
"sql",
"oracle",
"performance",
"select",
"view",
""
] |
I have 2 different tables employees and salaries the salaries table has multiple duplicate id's on it my question is how can i combined the employee and salaries table and removed its duplicate but i want the max salary to be displayed for that employee.
Employees table
[ it's a [Slowly Changing Dimension](https://en.wikipedia.org/wiki/Slowly_Changing_Dimension). Your data might look like this:
```
Emp_no salary from_date to_date
22 14000 2007-01-01 2008-03-31 -- or 2008-04-01
22 16000 2008-... | You need something like this. I created a fiddle demo with necessary columns.
```
select e.*, s.salary from
employees e
inner join
(
select emp_no,max(salary) as salary from salaries
group by emp_no
) s
on e.emp_no=s.emp_no
```
**See Fiddle demo here**
<http://sqlfiddle.com/#!9/b5b67/5> | combined 2 different structure tables and remove duplicates | [
"",
"mysql",
"sql",
""
] |
Here's the code that is in production:
```
dynamic_sql := q'[ with cte as
select user_id,
user_name
from user_table
where regexp_like (bizz_buzz,'^[^Z][^Y6]]' || q'[') AND
user_code not in ('A','E','I')
order by ... | I think that StackOverflow's formatting is causing some of the confusion in the answers. Oracle has a syntax for a string literal, `q'[...]'`, which means that the `...` portion is to be interpreted exactly as-is; so for instance it can include single quotes without having to escape each one individually.
But the code... | When not in couples `]` means... Well... Itself:
```
^[^Z][^Y6]]/
^ assert position at start of the string
[^Z] match a single character not present in the list below
Z the literal character Z (case sensitive)
[^Y6] match a single character not present in the list below
Y6 a single character in the list Y6 li... | What is this Oracle regexp matching in this production code? | [
"",
"sql",
"regex",
"oracle",
""
] |
I have a table with 51 records . The table structure looks something like below :
**ack\_extract\_id** **query\_id** **cnst\_giftran\_key** **field1** **value1**
Now ack\_extract\_ids can be 8,9.
I want to check for giftran keys which are there for extract\_id 9 and not there in 8.
What I tried was
```
... | When you test columns from the left-joined table in the where clause (`ack_flextable2.ack_extract_id` in your case), you force that join to behave as if it were an inner join. Instead, move that test to be part of the join condition.
Then to find records where that value is missing, test for a NULL key in the where cl... | **THIS IS NO ANSWER, JUST AN EXPLANATION**
From your comment to Joe Stefanelli's answer I gather that you don't fully understand the issue with WHERE and ON in an outer join. So let's look at an example.
We are looking for all supplier's last orders, i.e. the order records where there is no newer order for the suppli... | LEFT JOIN WHERE RIGHT IS NULL for same table in Teradata SQL | [
"",
"sql",
"left-join",
"teradata",
""
] |
Is there Go equivalent of Apple's GCD serial dispatch queue?
So far I have only found a solution that is a channel of functions.
```
work := make(chan func())
```
I would have a function receive from this channel and call the received functions. The functions must be executed in FIFO order.
Is there a better method... | @OneOfOne, it was close but not quite.
I ended up making a Serial Dispatch Queue implementation in Go available [here](https://github.com/ansonl/serialqueue).
It is basically a go routine that blocks on a `channel` of type `func()` and runs the functions that are passed in order.
**Implementation:**
```
//Package s... | Something like this should work, however I'm not familiar with how GCD works so I could be way off.
```
func main() {
q := NewQueue(10) // the size is mainly so it wouldn't block, you can play with that to your liking.
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
i := i
... | Go equivalent of GCD serial dispatch queue | [
"",
"sql",
"go",
"queue",
"grand-central-dispatch",
""
] |
I have a table of logins that looks like this:
logins table
```
Emp_ID Created | Action
1 20/01/2016 10:44:42 AM login
1 20/01/2016 4:45:49 PM logout
1 20/01/2016 6:30:13 PM logout
1 21/01/2016 8:46:28 AM login
1 21/01/2016 9:46:42 AM login... | First of all, cudos for a prefect question. Table structure, fiddle demo and expected output helps a lot.
Now I tried this and it is working in fiddle. Please recheck and let me know.
```
select t_login.emp_id,t_login.dt_created as created,t_login.login,
case when t_logout.logout is null
then cast('00:00:00' as ... | This is my suggestion (be aware of culture specific date literals. I had to set a language to get a correct date conversion):
```
SET LANGUAGE GERMAN;
DECLARE @logins TABLE(Emp_ID INT,Created DATETIME, Action VARCHAR(100));
INSERT INTO @logins VALUES
(1,'20/01/2016 10:44:42 AM','login')
,(1,'20/01/2016 4:45:49 PM','... | select columns into rows grouped by columns values | [
"",
"sql",
"sql-server-2008",
""
] |
Using Postgres 9.4, I am trying to select a single row from from a table that contains data nearest to, but not before, the current system time. The `datetime` colum is a `timestamp without time zone` data type, and the data is in the same timezone as the server. The table structure is:
```
uid | datetime |... | The general idea follows. You can adjust it for postgresql.
```
select fields
from yourTable
where datetimeField =
(select min(datetimeField)
from yourTable
where datetimeField > current_timestamp)
``` | You can also use this. This will be faster. But it wont make much difference if you have few rows.
```
select * from table1
where datetime >= current_timestamp
order by datetime
limit 1
```
`SQLFiddle Demo` | Select row with timestamp nearest to, but not later than, now | [
"",
"sql",
"postgresql",
""
] |
I'm working on a query right now that will count the number of unique login days per user, place them in a bucket (1-2, 3-4 log in days etc.), and return the number of each users in each bucket by department. I apologize if this isn't too clear, and hopefully the examples below will help illustrate my question.
I have... | Something like this?
```
select buckets, dept, count(user_name) no_of_u from
(select
(case when count(distinct(`time`)) between 1 and 2 then '1-2'
when count(distinct(`time`)) between 3 and 4 then '3-4'
else '5+'
end) as buckets, dept, user_name
from change_log where event in ('logged in') ... | But you can do it like this:
```
select
ELT(LEAST(count(*),5), '1-2', '1-2', '3-4', '3-4','5+') as buckets,
dept,
count(*) as `number of users`
FROM change_log where event in ('logged in')
WHERE event in ('logged in')
GROUP BY
dept,
ELT(LEAST(count((*),5), '1-2', '1-2', '3-4', '3-4','5+');
``` | MySQL - Group By Number of Users within Ranges of Unique Login Days and by Department | [
"",
"mysql",
"sql",
""
] |
I have table with column id,firstName,lastName,fullName and I want to copy the combined value of column firstName and lastName into fullName column.Is it possible by using query without stored procedure ?
As i know we can set the one column value to other using something like:
```
UPDATE table_name SET column1 = colu... | Use CONCAT function of mysql:
```
UPDATE table_name SET column1 = CONCAT(column2, ' ', column3);
``` | For `SQL Server`...
`COMPUTED` column:
```
ALTER TABLE dbo.tbl
ADD FullName AS firstName + ' ' + lastName
GO
```
Or permanent `UPDATE`:
```
UPDATE dbo.tbl
SET FullName = firstName + ' ' + lastName
``` | How to copy the combined value of two column to one Column in same table | [
"",
"mysql",
"sql",
"sql-server",
""
] |
I have a SQL select statement that is basically just
```
SELECT * FROM myTable
WHERE status != 5
```
It is a lot more complex than in reality, but its mostly convoluted column names and joins.
what i want to be able to do is on a parameter being a value, I disable the where clause, i.e.
```
SELECT * FROM myTable
... | You could do literally what you're asking (i.e. disable the where clause) using dynamic sql.
```
declare @ssql varchar(max)
set @ssql = 'SELECT * FROM myTable'
+ CASE WHEN @parameter = 'true' THEN ' WHERE status != 5' ELSE '' END
EXEC (@ssql)
```
However, it will be easier to read and modify in future if you can avo... | The following will work perfectly in your situation without any use of dynamic SQL. This is based on an assumption that `status` value can never take on a value of `-1`. You would need to come up with a similar value in your situation that status will never ever equal.
When @parameter is true then the query is like th... | SQL - Adding/Disabling a Where clause based on a boolean condition in Select Statement (ASP.net SQLDataSource) | [
"",
"sql",
"asp.net",
"sql-server",
"vb.net",
"t-sql",
""
] |
Can I modify the next to use the column aliases `avg_time` and `cnt` in an expression `ROUND(avg_time * cnt, 2)`?
```
SELECT
COALESCE(ROUND(stddev_samp(time), 2), 0) as stddev_time,
MAX(time) as max_time,
ROUND(AVG(time), 2) as avg_time,
MIN(time) as min_time,
COUNT(path) as cnt,
ROUND(av... | You can use a previously created alias in the `GROUP BY` or `HAVING` statement but not in a `SELECT` or `WHERE` statement. This is because the program processes all of the `SELECT` statement at the same time and doesn't know the alias' value yet.
The solution **is to encapsulate the query in a subquery and then the al... | The order of execution of a query (and thus the *evaluation* of expressions and aliases) is NOT the same as the way it is written. The "general" position is that the clauses are evaluated in this sequence:
```
FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY
```
Hence the *column aliases* are unknown to most of the query *... | Why can't I use column aliases in the next SELECT expression? | [
"",
"sql",
"postgresql",
"column-alias",
""
] |
I'm currently building a YTD report in SSRS. I'm looking to edit the default "FROM" date in a calendar selection.
I'm looking to retrieve January 1st of the previous months year. For example:
(If it's Feb 16th, 2016 .. the result should be **1/1/2016**
If it's Jan 10th, 2016 .. the result should be **1/1/2015**)
I ... | Try this, it should work
```
=DateAdd(DateInterval.Month,-1,DateSerial(Year(Today), Month(Today), 1))
```
**UPDATE:**
Based on your comment I've created this expression. It is not tested but should work.
```
=IIF(Today.Month>1,
DateAdd(DateInterval.Month,-1,DateSerial(Year(Today), Month(Today), 1)),
DateAdd(DateInt... | ```
select cast(cast(year(dateadd(mm, -1,getdate())) as varchar)+'-01-01' as date)
```
replace getdate() with which ever field you're basing this calculation on.
for testing:
```
select cast(cast(year(dateadd(mm, -1,'2015-01-22')) as varchar)+'-01-01' as date)
select cast(cast(year(dateadd(mm, -1,'2016-02-01')) as v... | Get Year of Previous Month (For Jan 1st) | [
"",
"sql",
"sql-server",
"reporting-services",
""
] |
I have a function like this in SQL Server. I can not understand what is it. Can anyone please explain it to me briefly?
```
6371 * ACOS(ROUND(
COS(RADIANS(Latitude1)) *
COS(RADIANS([Latitude2])) *
COS(RADIANS(Longitude1) - RADIANS(Longitude2)) +
SIN(RADIANS(Latitude1)) ... | You are looking at the Haversine formula, which computes the distance on a sphere using their latitude and longitude coordinates. Here is a query using the full Haversine formula:
```
SELECT
ACOS(
COS(RADIANS(Latitude1))
* COS(RADIANS(Latitude2))
* COS(RADIANS(Longitude1) - RADIANS(Longitude2))
... | Just like @TimBiegeleisen and @RobertRodkey have said, it's an old school formula for calculating the distance between two points on a Earth.
So this leads to some other questions:
1. Q: Doesn't SqlServer have geospatial methods available? A: **Yes** for sql server version 2008 and later.
2. Q: If Sql has this availa... | Query using Longitude and Latitude in SQL Server | [
"",
"sql",
"sql-server",
""
] |
I have a table of logins that looks like this:
```
Created | Action
20/01/2016 08:00:00 AM login
20/01/2016 10:05:10 AM logout
20/01/2016 12:00:00 PM login
20/01/2016 04:12:22 PM logout
21/01/2016 08:00:50 AM login
21/01/2016 09:44:42 AM login
21/01/2016 10:44:42 AM login
21/01/201... | Similar to Rahul's answer, but you can do a self join to get first login/last logout and just group by the date to get the result you're asking for;
```
SELECT CONVERT(DATE, li.created) [Date],
CONVERT(TIME, MIN(li.created)) [Login],
CONVERT(TIME, MAX(lo.created)) [Logout]
FROM Logins li
JOIN Log... | You can try like this:
```
SELECT
CONVERT(VARCHAR(10),li.Created,10) [Date],
CONVERT(VARCHAR(8),MAX(li.Created),8) [Login],
CONVERT(VARCHAR(8),MAX(lo.Created),8) [Logout]
From Logins li
Left Join Logins lo on lo.[Action] = 'logout'
GROUP BY CAST(li.Created AS DATE)
```
ie, you need to group by your records on t... | select group same column by date into different column | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
```
Server version: 5.7.10 MySQL Community Server (GPL)
```
In MySQL, I have a user mangos. The user worked perfectly when I created it. After rebooting my computer, though, attempting to login to mangos yielded this output:
```
$ mysql -u mangos -p
Enter password:
ERROR 1524 (HY000): Plugin '*some_random_long_hash_... | It appears your user table is corrupted. Likely the reboot you mentioned triggered an upgrade to MySQL and the `mysql_upgrade` script was not run. This should resolve the situation:
```
mysql_upgrade -u root -ppassword --skip-grant-tables
mysql -u root -ppassword -e "UPDATE mysql.user SET plugin = 'mysql_native_passwo... | `mysql_upgrade` (suggested by @miken32) wasn't working for me, so I had to do it the hard way, by shutting down the service and using `mysqld_safe`, as explained [here](https://askubuntu.com/questions/489098/unable-to-reset-root-password-of-mysql/671593#671593).
**UPDATE**: Actually, that didn't work either, so I had ... | MySQL Won't let User Login: Error 1524 | [
"",
"mysql",
"sql",
""
] |
Say I have some data like:
```
grp v1 v2
--- -- --
2 5 7
2 4 9
3 10 2
3 11 1
```
I'd like to create new columns which are independent of the ordering of the table - such that the two columns have independent orderings, i.e. sort by v1 independently of v2, while partitioning by grp.
... | I think you are in right direction! You just need to use proper window function . Row\_number() in this case. And it should work!
Adding working example as per @cgn request:
I dont think there is way to totally avoid use of JOIN.
At the same time below example uses just **ONE JOIN** vs **TWO JOIN**s in other answe... | This will work for you.
`SQLFiddle Demo in SQL Server`
Note: The sequence you mentioned in the sample, is not necessary how the rows are returned from database. In my case, for `v1`, I got `4,5,10,11` unlike your `5,4,10,11`. However, your output will be same as you wanted.
```
Select t.grp,t.v1,t.v2,
v1.v1 as v1_or... | Google BigQuery SQL: Order two columns independently | [
"",
"sql",
"sorting",
"google-bigquery",
"window-functions",
"database-partitioning",
""
] |
I'm selecting one customer from `customers` table and trying to get the latest order number for the customer from a `jobs` table, but based on a different timestamp column in that table.
**Customers**
```
id | name | ...
```
**Jobs**
```
id | customer_id | order_id | assigned
----------------------------------... | Use one more derived table to get the order number for the latest order.
```
SELECT c.name, t.order_id, j.latest_order
FROM customers c
JOIN (
SELECT customer_id,
max(assigned) AS latest_order
FROM jobs
WHERE withdrawn IS NULL
GROUP BY customer_id
) j ON j.customer_id = c.id
JOIN (select cu... | I'm not sure if this is the fastest way but maybe you want to try an explain against the alternate answer to compare both performances:
```
SELECT c.name, j.latest_order
FROM customers c
LEFT JOIN (
SELECT j1.customer_id, j1.order_id
FROM jobs j1
JOIN (
SELECT customer_id, max(assigned) as maxassigned
... | MySQL - Join order number of latest order based on timestamp | [
"",
"mysql",
"sql",
""
] |
I would like to maintain a system for uploading data through Excel to SQL Server with ADO method. The process consists of two steps:
1. the raw data is inserted to temporary table, say `dbo.TableTemp`
2. the raw data is processed with a stored procedure and inserted to a `dbo.GoodTable`
3. `delete from dbo.TableTemp` ... | Use [temporary tables](https://technet.microsoft.com/en-us/library/ms177399(v=sql.105).aspx) `#TableTemp`. Those are specific for each session and thus would not overlap.
> There are two types of temporary tables: local and global. They differ
> from each other in their names, their visibility, and their
> availabilit... | Another approach - use `TABLE` variable. [From MSDN](https://msdn.microsoft.com/en-us/library/ms175010.aspx)
```
CREATE @AddedValues TABLE (ID INT, SomeValue VARCHAR(50))
```
Then use it normally as tables in the query.
```
INSERT INTO @AddedValues (ID, SomeValue) VALUES (1, 'Test');
SELECT ID FROM @AddedValues WHE... | Handling insert and delete with multiple users in SQL | [
"",
"sql",
"sql-server",
""
] |
I have a table as follows
```
Col1 Col2
12 34
34 12
```
Considering, these are duplicates how we delete them?
I tried solving this question using self joins. But I am not able to get the required answer. Can someone help? | you can use [GREATEST](http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_greatest) and [LEAST](http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_least) to 'order' your columns, and then use distinct:
```
SELECT DISTINCT GREATEST(col1, col2) as first, LEAST(col1, col2) as... | I assume you want to have a symmetric relation: for example, if A is a friend of B, then B is also a friend of A? I also assume that both columns are foreign IDs, and numeric. If this is not so, you will have to adapt.
The best way is to never ever insert the two versions at all; normalise the relation so that the sma... | How to remove duplicate tuples using SQL | [
"",
"mysql",
"sql",
""
] |
Given a table structured like that:
```
id | news_id(fkey)| status | date
1 10 PUBLISHED 2016-01-10
2 20 UNPUBLISHED 2016-01-10
3 10 UNPUBLISHED 2016-01-12
4 10 PUBLISHED 2016-01-15
5 10 UNPUBLISHED ... | First of all, subqueries are a substantial part of SQL. A framework forbidding their use is a bad framework.
However, "first" and "last" can be expressed with NOT EXISTS: where not exists an earlier or later entry for the same news\_id and date range.
```
select count(*)
from mytable first
join mytable last on last.n... | Not sure if this adresses you problem correctly, since it is more of a workaround. But considering the following:
News need to be published before they can be "unpublished". So if you'd add 1 for each "published" and substract 1 for each "unpublished" your balance will be positive (or 1 to be exact) if first and last ... | Count how many first and last entries in given period of time are equal | [
"",
"sql",
"database",
"hibernate",
"postgresql",
"hql",
""
] |
I have a table with Transactions, amongst whose columns are `id`, `created_at`, and `company_id`. I'd like to group the four first transactions of every company and return the created\_at values of each transaction on each row.
In other words, I want each row of my output to correspond to the four first transactions o... | ```
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,company_id VARCHAR(12) NOT NULL
,created_at DATE NOT NULL
);
INSERT INTO my_table VALUES
( 1123,'abcd','2015/10/12'),
( 8291,'abcd','2015/10/14'),
( 9012,'abcd','2015/10/15'),
( 9540,'abcd','2015/10/16'),
(10342,'abc... | One possible way is the following:
```
select company_id,
min(created_at) as created_at_1,
(select created_at from t where company_id=t1.company_id order by created_at limit 1 offset 1) as created_at_2,
(select created_at from t where company_id=t1.company_id order by created_at limit 1 offset 2) as creat... | Group exactly four rows sql | [
"",
"mysql",
"sql",
""
] |
I have the following text:
```
Price is .....
return policy is....
Mega's accept....
```
I want to insert this whole text into a column of type `TEXT`
What I wrote was:
```
Insert into A (id,msg) values (5, ' Price is .....
return policy is....
Mega's store online ....')
```
`Mega's` is the name of ... | If you don't want to (or can't) change the actual text, use [dollar quoting](http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-DOLLAR-QUOTING). Just replace the first and last `'` with e.g. `$$`:
```
Insert into A (id,msg) values (5, $$ Price is .....
return policy is....
Mega... | You can just double the single quote inside the string: `'Mega''s store online'`.
Alternatively, you can pass any string through the function `quote_literal()` and that will then take care of proper quoting and other issues such as [SQL-injection](http://bobby-tables.com). That is useful when the string comes from som... | How to enter text with ' into table? | [
"",
"sql",
"postgresql",
""
] |
SQL Server 2014 database. Table with 200 million rows.
Very large query with HUGE IN clause.
I originally wrote this query for them, but they have grown the IN clause to over 700 entries. The CTE looks unnecessary because I have omitted all the select columns and their substring() transformations for simplicity.
The... | I recommend you store your 700+ strings in a permanent table as it is generally perceived as bad practice to store that much meta data in a script. You can create the table like this:
```
CREATE TABLE dbo.LookUp(Source varchar(250), Target varchar(250))
CREATE INDEX IX_Lookup_Source_Target on dbo.Lookup(Source,Target... | Put all of your codes into a temporary table (or permamnent if suitable).....
```
SELECT *
FROM AODS-DB1B
INNER JOIN NEW_TABLE ON Source+'-'+Target = NEWTABLE.Code
WHERE
...
...
``` | SQL Server query with extremely large IN clause results in numerous queries in activity monitor | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
In my application I've got "articles" (similar to posts/tweets/articles) that are tagged with descriptive predefined tags: i.e "difficult", "easy", "red", "blue", "business" etc
These available tags are stored in a table, call it "tags" that contains all available tags.
Each article can be tagged with multiple tags, ... | I think you should read about [Database normalization](https://en.wikipedia.org/wiki/Database_normalization) and decide for yourself. In short though, there are a number of issues with your proposal, but you may decide you can live with them.
The most obvious are:
1. What if an additional tag is added to row(1)? Do y... | It seems to me like you want to have a separate table that stores tags and holds a foreign key which relates the tag records back to their parent record in the articles table (this is referred to as "normalizing" the database structure).
Doing it like you have suggested by cramming the tags into one field may seem to ... | Is it ever a good idea to store an array as a field value, or store array values as records? | [
"",
"sql",
"database",
"postgresql",
"database-design",
""
] |
I am trying to write a SQL query in SQL Server 2008 R2 that will allow a user to search a database table by a number of parameters. The way this should work is, my user enters his criteria and the query looks for all close matches, while ignoring those criteria for which the user did not enter a value.
I've written my... | Thanks for the guidance, all. It turns out that the table I'm querying can easily contain null values in the columns I'm searching against, so I expanded my query to say "where (a like @a or a is null) and ... " and it works now. | To allow for null inputs, this is a good pattern:
```
select * from my table where ColA LIKE isnull(@a, ColA) AND ColB like isnull(@b, ColB)
```
This avoids having to construct and execute a dynamic SQL statement (and creating possible SQL injection issues.) | How can I search a SQL database with multiple "%" wildcards? | [
"",
"sql",
"sql-server-2008-r2",
""
] |
I have the following two tables:
```
Table A
+-------------------+
|___User___|__Value_|
| 3 | a |
| 4 | b |
| 5 | c |
|____6_____|__d_____|
Table B
+-------------------+
|___User___|__Value_|
| 1 | |
| 4 | |
| 5 | |
|____... | Could be this
```
update table_b as b
inner join table_a as a on a.User = b.User
set b.value = a.value
``` | In real-world situations, it would be more likely that you want a predictable value, such as the greatest `value` for any given `user`. In that case you would want
```
update table_b as b
inner join (
select user, max(value) from table_a
group by user ) as a_max on a.user = b.user
set b.value = a_max.value
``` | SQL: Update table by mapping two columns to each other | [
"",
"mysql",
"sql",
"database",
""
] |
There is a query I am trying to implement in which I am not having much success with in trying to find the MAX and MIN for each week.
I have 2 Tables:
SYMBOL\_DATA (contains open,high,low,close, and volume)
WEEKLY\_LOOKUP (contains a list of weeks(no weekends) with a WEEK\_START and WEEK\_END)
```
**SYMBOL_DATA Exam... | [SQL Fiddle](http://sqlfiddle.com/#!9/f156d/4)
I have abbreviated some of your names in my example.
Getting the high and low for each week is pretty simple; you just have to use GROUP BY:
```
SELECT s1.symbol, w.week_end, MAX(s1.high) AS weekly_high, MIN(s1.LOW) as weekly_low
FROM weeks AS w
INNER JOIN symdata AS s1... | The week table seems entirely redundant...
```
SELECT symbol
, WEEK(zdate)
, MIN(low) min
, MAX(high) max_high
FROM symdata
GROUP
BY symbol, WEEK(zdate);
```
This is a simplified example. In reality, you might use DATE\_FORMAT or something like that instead.
<http://sqlfiddle.com/#!9/c247f/3> | Finding MAX and MIN values for each same start and end week | [
"",
"mysql",
"sql",
""
] |
```
SELECT
COUNT(emp.empNo)
FROM
Employee emp
WHERE
NOT EXISTS (SELECT dept.empNo
FROM department dept
WHERE emp.empNo = dept.empNo);
```
What does the `where` condition(where emp.empNo = dept.empNo) signify in the above query? I get different results with and without the wh... | The query means that you're looking for only those employees, for which it does not exist a department with the same empNo as the employee's empNo.
I guess this is a query to find those employees which are not managers of any department (if we assume that the department's empNo is the empNo of the department's manager... | your query displaying count of employees which are not present in emp table but present in dept table.
suppose we have two tables emp and dept :
```
emp dept
1 1
2 2
3 3
4 4
5 5
6
7
```
from the given table we have emp ... | What does where do in the below query? | [
"",
"sql",
"oracle11g",
"oracle10g",
""
] |
Need some help in writing the SQL query for SQL Server. I have following data model with three tables
Table 1
```
Seq ID Name
1 1234 Abc
2 4567 Pqr
3 7890 Xyz
```
Table 2
```
Seq Table1Id Table3Seq
1 1234 1
2 1234 2
3 7890 3
```
Table 3
```
Seq Status
1 Rejected
2... | ```
select a.ID, a.Name, c.Status
from table1 a
left outer join (select max(b.seq) AS SEQ, b.table1id from table2 b group by b.table1id) t2 on a.id = t2.table1id
left outer join table2 t2b on t2.seq = t2b.seq and t2.table1id = t2b.table1id
left outer join table3 c on t2b.table3seq = c.seq
```
There are probably more e... | One way of doing this in SQL Server is using `outer apply`. This method often has the best performance:
```
select t1.*, t3.status
from table1 t1 outer apply
(select top 1 t3.*
from table2 t2 join
table3 t3
on t2.table3seq = t3.seq
where t1.id = t2.table1id
order by t2.id d... | SQL Server - Inner and Outer join together | [
"",
"sql",
"sql-server",
"inner-join",
"outer-join",
""
] |
I have two tables: `users` and `userlogs`
```
table1
----------
id | name
----------
1 | A
2 | B
3 | C
4 | D
table2
----------
user_id | date
----------
1 | 2015-12-17
2 | 2015-12-18
3 | 2015-12-19
4 | 2015-12-20
```
If I do LEFT JOIN with selected date, it only gives data that exist in table 2.
```
SELECT r.user_... | This query should do just fine:
```
DECLARE @T1 TABLE
(
id INT
, name VARCHAR(50)
);
DECLARE @T2 TABLE
(
[user_id] INT
, [date] DATE
);
INSERT INTO @T1 (id, name)
VALUES (1, 'A'), (2, 'B'), (3, 'C'), (4, 'D');
INSERT INTO @T2 ([user_id], [date])
VALUES (1, '2015-12-17'), (2, '2015-12-18'), (3, '2015... | Try moving the filter condition into the left join.
```
SELECT
a.id,
count(r.user_id) as count
FROM table1 a
LEFT OUTER JOIN table2 r ON r.user_id = a.id AND
r.created_at BETWEEN '2015-12-17' AND '2015-12-19'
GROUP BY a.id
``` | SQL query left joining issue | [
"",
"mysql",
"sql",
"sql-server",
"join",
"left-join",
""
] |
I have two tables, assets and asset\_params.
assets
```
|asset_id| some_asset_data |
-----------------------------
| 1 | 'some data' |
| 2 | 'some other data'|
```
asset\_params
```
|asset_param_id|asset_id|param_name|param_value|
------------------------------------------------
| 1 |... | ```
select * from assets a where
exists (select 1 from asset_params p
where name = "OS" and value = "Win" and a.asset_id=p.asset_id)
and exists (select 1 from asset_params p
where name = "memory" and value = "4096" and a.asset_id=p.asset_id)
``` | You can do this with aggregation and a `having` clause:
```
select asset_id
from asset_params
where param_name = 'Memory' and param_value = '3096' or
param_name = 'OS' and param_value = 'Windows'
group by asset_id
having count(*) = 2;
```
Note: if you can have multiple parameters with the same name, you should ... | sql check if join table has rows by mutliple criterias | [
"",
"sql",
"postgresql",
""
] |
I've a query like this:
```
select tractions.id,tractions.expired,tractions.succ,tractions.cradit_end_date,
tractions.user_id,users.family,tractions.coupon_code,users.username,traction_details.title,
traction_details_sub.title as sub_title,tractions.coupon_parent,tractions.coupon_... | Switch to ANSI joins (they have been nearly universally available for a long time) and use an outer join for tables that may not have records:
```
SELECT
t.id
, t.expired
, t.succ
, t.cradit_end_date
, t.user_id
, u.family
, t.coupon_code
, u.username
, d.title
, s.title as sub_title
, t.coupon... | First select all tr\_id from traction\_details and after repeat you sql query add condition IN tractions.id (all id available) | using join if there is a record | [
"",
"mysql",
"sql",
""
] |
I haven't had much experience with SQL and it strikes me as a simple question, but after an hour of searching I still can't find an answer...
I have a table that I want to add up the totals for based on ID - e.g:
```
-------------
ID Quantity
1 30
2 11
1 4
1 3
2 17
3... | ```
Select ID, Sum(Quantity) from YourTable
Group by ID
```
You can find here some resources to learn more about "Group by": <http://www.w3schools.com/sql/sql_groupby.asp> | ```
SELECT ID, SUM(QUANTITY) FROM TABLE1 GROUP BY ID ORDER BY ID;
``` | totalling rows for distinct values in SQL | [
"",
"sql",
""
] |
I have a database table (Oracle 11g) of questionnaire feedback, including multiple choice, multiple answer questions. The Options column has each value the user could choose, and the Answers column has the numerical values of what they chose.
```
ID_NO OPTIONS ANSWERS
1001 Apple ... | It's slow because you're expanding each row too many times; the connect-by clauses you're using are looking across all the rows, so you're ending up with a huge amount of data to then sort - which is presumably why you ended up with the `DISTINCT` in there.
You can add two `PRIOR` clauses to the connect-by, firstly so... | Check out this compact solution:
```
with sample_data as
(
select 'ala|ma|kota' options, '1|2' answers from dual
union all
select 'apples|oranges|bacon', '1|2|3' from dual
union all
select 'a|b|c|d|e|f|h|i','1|3|4|5|8' from dual
)
select answers, options,
regexp_replace(regexp_replace(options,'([^|]+)\|([... | SQL Regex - Replace with substring from another field | [
"",
"sql",
"regex",
"oracle",
"regexp-replace",
"regexp-substr",
""
] |
I have q query like this:
```
Select WarehouseCode from [tbl_VW_Epicor_Warehse]
```
my output looks like this
```
WarehouseCode
Main
Mfg
SP
W01
W02
W03
W04
W05
```
But sometimes I want to get W04 as the first record, sometimes I want to get W01 as the first record .
How I can write a query to get some records i... | you could try and select the row with the code you want to appear first by specifying a where condition to select that row alone then you can union all another select with all other rows that doesn't have this name
as follows
> ```
> SELECT WarehouseCode FROM Table WHERE WarehouseCode ='W04'
> UNION ALL
> SELECT War... | Use a parameter to choose the top row, which can be passed to your query as required, and sort by a column calculated on whether the value matches the parameter; something like the `ORDER BY` clause in the following:
```
DECLARE @Warehouses TABLE (Id INT NOT NULL, Label VARCHAR(3))
INSERT @Warehouses VALUES
(1,'W01'... | how to get some records in first row in sql | [
"",
"sql",
"sql-server",
"select",
""
] |
I'm trying to create a software for a gym but I'm getting this error and I don't know why, I've trying for hours but nothing
```
CREATE TABLE Socios (
IdSocio INT NOT NULL AUTO_INCREMENT,
Nombre VARCHAR(30) NOT NULL,
Apellido VARCHAR(30) NOT NULL,
N_Celular VARCHAR(12),
Correo VARCHAR(60),
Fe... | This will get you over an initial hurdle. Though I doubt you really want an FK on a price but I don't know the translation into your mother tongue.
You need indexes on the *referenced* tables for the columns looked up in FK's.
```
create schema dbtest_xyz;
use dbtest_xyz;
-- drop table Socios;
CREATE TABLE Socios... | Your first 2 tables should be as per below, means referenced fields should be indexed.
```
CREATE TABLE Socios (
IdSocio INT NOT NULL AUTO_INCREMENT,
Nombre VARCHAR(30) NOT NULL,
Apellido VARCHAR(30) NOT NULL,
N_Celular VARCHAR(12),
Correo VARCHAR(60),
Fecha_Nacimiento DATE NOT NULL,
Fecha_... | Error Code: 1215. Cannot add foreign key constraint | [
"",
"mysql",
"sql",
"sql-server",
""
] |
```
SELECT
externalsource.id,
externalsource.url,
externalsource.last_fetch,
SUM(scripttracking.records) AS jobs_per_week
FROM
scripttracking
RIGHT JOIN
externalsource
ON
externalsource.script_name = scripttracking.script_name
AND
scripttracking.created_on > %s
GROUP BY
externalsourc... | Traditionally we'd use `CASE` statement but Postgres offers us more comfortable solution so better to use [FILTER](http://www.postgresql.org/docs/current/static/sql-expressions.html)
```
SELECT
externalsource.id
,externalsource.url
,externalsource.last_fetch
,SUM(scripttracking.records) AS jobs_per_wee... | Using a case statement to evaluate the values to sum otherwise use a 0.
Note this is inclusive logic so sum of month contains sum of week, and sum of year contains some of week and month.
```
SELECT
externalsource.id,
externalsource.url,
externalsource.last_fetch,
SUM(case when scripttracking.created_... | How to aggregate fields with different AND clause within RIGHT JOIN? | [
"",
"sql",
"django",
"postgresql",
""
] |
I was presented with the question:
*Write a SQL command to display for each employee who has a total
distance from all journeys of more than 100, the employee’s name,
the total number of litres used by the employee on all journeys. (The
number of litres for a journey is distanceInKm divided by kmPerLitre.)*
For the f... | Here is a version that joins your tables and should give you what you expect
```
SELECT E.NAME
, SUM(T.distanceInKM/C.kmPerLitre) AS NumLitres
, SUM(T.distanceInKM) AS TotalDistanceInKm
FROM Employe E
INNER
JOIN TravelCost T
ON E.id = T.employeeId
INNER
JOIN CAR C
ON T.carRegNo = C.regNo
GR... | try it like this:
```
DECLARE @Employee TABLE(id INT,name VARCHAR(100));
INSERT INTO @Employee VALUES
(1,'Smith')
,(2,'Patel')
,(6,'Bennett')
,(7,'Booch');
DECLARE @Car TABLE(regNo VARCHAR(100),distanceSinceService INT,kmPerLitre FLOAT);
INSERT INTO @Car VALUES
('FF06DDS',122,10)
,('EE07SSA',110,8)
,('FG07BAK',165,... | Some problems with extracting data from three separate tables | [
"",
"sql",
""
] |
By mistake I've added one column in my database Named as `doj` now if I want to drop that column from table using code first approach what should I do.
I've tried this things.
1- Removing the column definition from model.
2- Deleted Migration history.
3- Add-migration
4- Update database.
But still it is not re... | Don't need to delete migration history.
Just follow these steps
```
1: Remove properties from the model.
2: Run 'Enable-Migrations' in package manage console.
3: Next Run 'Add-Migration "MigrationsName"'. if any case it is showing 'The project tesproject failed to build then build project again.
4: Now run 'Update-D... | While Neeraj's answer is correct and in most cases works well, if that column has previous data in it, it will be removed from the index, but the data will still be there (and the column, for that matter).
To completely remove the column (and data in it), use the `DropColumn()` method. To accomplish this, create a new... | How can we delete a column from sql table by using code first approach in EF 6.0? | [
"",
"sql",
"asp.net-mvc",
"entity-framework",
""
] |
Trying to figure out how to get my data to return the SELECT data first and then display the UNION data below. Currently it is returning the UNION data first two rows and SELECT data after. I need the SELECT on Top and the UNION on bottom. Tried a few ways but nothing is working.
```
SELECT
Recor... | Introduce an artificial sort key column (I'll call it `MySortKey` in the code sample below) to keep the two selects separated.
```
SELECT
Record_Time_Stamp AS 'Record_Time_Stamp',
Car_ID,
Commodity,
CAST(Transaction_Num AS NVARCHAR(MAX)) AS 'Transacti... | You could add own column:
```
SELECT ..., 1 AS query_num
FROM ...
UNION
SELECT ..., 2 AS query_num
FROM ...
UNION
SELECT ..., 3 AS query_num
FROM ...
ORDER BY query_num, ...
```
Keep in mind that adding column will circumvent `UNION` distinctness, so you could change it `UNION ALL`. | SQL - UNION - How to Manipulate Data Returned | [
"",
"sql",
"union",
""
] |
What is wrong with this syntax:
```
DELETE FROM customer WHERE id IN ('1,3')
```
Customer table:
[](https://i.stack.imgur.com/vBEdn.png)
It deletes only the row with id = 1. I'm expecting empty table. If I leave there only one row with id=3, it say... | No need for `'` around values:
```
DELETE FROM customer WHERE id IN (1,3);
``` | You are looking for a single value that is a string with three characters: `'1,3'`, not two numeric values.
If you are constructing the query, then you should try to construct it with a proper `in` list. Under some circumstances, you might find it more convenient to use `find_in_set()`:
```
DELETE FROM customer WHERE... | Can't delete using IN | [
"",
"mysql",
"sql",
""
] |
I have two tables (about 300,000 rows each table) with one column identifier column (ID) that is indexed. The following query takes a few seconds:
```
SELECT *
FROM Table_1 a JOIN Table_2 b on a.ID=b.ID
```
Versus the following query which takes hours:
```
SELECT *
FROM Table_1 a LEFT JOIN Table_2 b on a.ID=b.ID
```... | With the information provided, I can only think of trying something like this:
```
SELECT a.*, b.column1, b.column2, ..., column(n)
FROM Table_1 a JOIN Table_2 b on a.ID=b.ID
UNION
SELECT a.*, '' AS column1, '' AS column2, ..., '' as column(n)
FROM Table_1 a
WHERE a.ID NOT IN
(SELECT a.ID FROM Table_1 a JOIN T... | JOIN is equivalent to INNER JOIN, so the first query will return rows *only* where the IDs match. The index here helps performance too.
Your second query performs a LEFT JOIN, which as you pointed out returns everything from table A, regardless if it matches something in table B. | "Join" between two tables is very fast versus "Left join" which is extremely slow (MySQL DB) | [
"",
"mysql",
"sql",
"performance",
""
] |
I have declared a string as shown below:
```
Declare @string
Set @string = 'this line is like this because this is repeated these many times in this line'
```
I am trying find that how many times each word is repeated. I am expecting a result like
```
Word Number
this x times
line y times
is z times
```... | ```
;WITH splitString(val) AS
(
-- convert the string to xml, seperating the elements by spaces
SELECT CAST('<r><i>' + REPLACE(@string,' ','</i><i>') + '</i></r>' AS XML)
)
SELECT [Key],
COUNT(*) [WordCount]
FROM ( -- select all of the values from the xml created in the cte
S... | Using a t-sql splitter this is pretty straight forward. My personal preference is the Jeff Moden splitter which can be found here. <http://www.sqlservercentral.com/articles/Tally+Table/72993/> There are some other options which can be found here. <http://sqlperformance.com/2012/07/t-sql-queries/split-strings>
Using Je... | How many times does each word is repeated in a string in sql server? | [
"",
"sql",
"sql-server",
""
] |
I'm using SQL server 2014,I'm fetching data from a view.The order of items is getting changed once i use **Group by** ,how can i get the order back after using this Group by,There is one date column,but its not saving any time,So i can't sort it based on date also..
How can I display the data in the same order as it di... | Tables and views are essentially unordered sets. To get rows in a specific order, you should always add an `ORDER BY` clause on the columns you wish to order on.
I'm assuming you previously selected from the `VIEW` without an `ORDER BY` clause. The order in which rows are returned from a `SELECT` statement **without**... | The only way you can enforce a specific order is to explicitly use a `ORDER BY` clause. Otherwise the order of rows is not guaranteed ([take a look at this article](http://blogs.msdn.com/b/conor_cunningham_msft/archive/2008/08/27/no-seatbelt-expecting-order-without-order-by.aspx) for more details) and the database engi... | how to resolve this - group by changes the Order of items in SQL Server | [
"",
"sql",
"sql-server",
""
] |
We are doing this:
```
SELECT x from d where x not in
(
SELECT xx FROM a
INNER JOIN aa ON a.col = aa.col
UNION
SELECT xx FROM b
INNER JOIN bb on a.col = bb.col
)
```
When we run sub query separately, it executes in 10 seconds and returns 0 records because one of the tables used in INNER JOIN is blank
But, when we ... | Sounds like the subquery is getting run for every x in d. Try it as a CTE, and if that fails a temp table, to pre-compute the subquery and only then use it to exclude records from x.
```
--CTE:
WITH subq AS
(
SELECT xx FROM a
INNER JOIN aa ON a.col = aa.col
UNION
SELECT xx FROM b
INNER JOIN bb on a.col = bb.col
)
SE... | Try this
```
select x from d
where not exists(Select top 1 1 from a inner join aa on a.col = aa.col where d.x = xx)
and not exists (Select top 1 1 from b inner join bb on a.col = bb.col where d.x = xx)
``` | Query Hangs when NOT IN is used with a SUBQUERY which returns NULL | [
"",
"sql",
"sql-server",
""
] |
I have a table which has two columns **UNIT**, **M\_UNIT** as shown below:
```
+------+--------+
| UNIT | M_UNIT |
+------+--------+
| 10 | 12 |
| 15 | 19 |
| 12 | 16 |
| 13 | 15 |
| 19 | 14 |
| 14 | 11 |
+------+--------+
```
I want to create a column **H\_TREE** which stores hier... | This should produce what you want:
```
WITH data (unit, m_unit) AS (
SELECT 10, 12 FROM dual UNION ALL
SELECT 15, 19 FROM dual UNION ALL
SELECT 12, 16 FROM dual UNION ALL
SELECT 13, 15 FROM dual UNION ALL
SELECT 19, 14 FROM dual UNION ALL
SELECT 14, 11 FROM dual)
SELECT
unit,
m_unit,
... | You should not do it this way. You should have a column called ParentID or something. Then build the tree when needed.
This is an example (SQL Server) that wires it all together:
```
USE AdventureWorks2008R2;
GO
WITH DirectReports (ManagerID, EmployeeID, Title, DeptID, Level)
AS
(
-- Anchor member definition
SELE... | Create column that stores hierarchy as comma separated values | [
"",
"sql",
"hierarchy",
"hierarchical-data",
""
] |
I have two tables. one table is named Shopper and it looks like
```
SHOPPER_ID | SHOPPER_NAME |
-------------------------
1 | Marianna |
2 | Jason |
```
and another table named Order has information like Date on the order
```
ORDER_ID | SHOPPER_ID | DATE
-------------------------------... | I suggest using a sub-select:
```
Select s.SHOPPER_ID, s.SHOPPER_NAME, o.MAX_DATE
from Shopper s
INNER join (SELECT SHOPPER_ID, MAX(DATE) AS MAX_DATE
FROM ORDER
GROUP BY SHOPPER_ID) o
on s.SHOPPER_ID = o.SHOPPER_ID
```
Best of luck. | Easy way is use `row_number` to find the lastest order
**[SQL Fiddle Demo](http://sqlfiddle.com/#!6/78546/2)**
```
SELECT *
FROM
(SELECT S.*,
O.[ORDER_ID], O.[DATE],
ROW_NUMBER() OVER ( PARTITION BY S.SHOPPER_ID
ORDER BY [DATE] DESC) as rn
FROM Sh... | One to many join with group by | [
"",
"sql",
"sql-server",
"greatest-n-per-group",
""
] |
I want to update big table `TEMP_MA_CONTACT` and I use `MERGE INTO`:
```
MERGE INTO TEMP_MA_CONTACT C
USING (select * from TABLE_TO_CHANGE_2601) T
ON (C.CUSTOMER_RK = T.CUSTOMER_RK)
WHEN MATCHED THEN UPDATE SET C.CUSTOMER_RK = T.NEW_CUSTOMER_RK
```
but Oracle says:
```
ORA-38104: Columns referenced in the ON Clause ... | The best variant to resolve this problem is:
1) First add rowid to table\_to\_change\_2601
```
CREATE TABLE table_to_change_2601_new AS
SELECT T.*,
I.ROWID AS ROW_ID FROM
table_to_change_2601 T JOIN temp_ma_contact I ON T.CUSTOMER_RK = I.CUSTOMER_RK
```
2) Merge on this rowid's
```
MERGE INTO temp_ma_c... | Mmmm, I'm not sure if it is possible with merge.. but you can always use update with a subquery:
```
UPDATE TEMP_MA_CONTACT C
set c.customer_rk =
(select P.new_customer_rk from table_to_change_2601 p where P.customer_rk = C.customer_rk)
```
Another idea is this:
```
ALTER TABLE TEMP_MA_CONTACT add TEMP_COL NUMBER(5)... | SQL How can I avoid ora-38104? | [
"",
"sql",
"oracle",
"merge",
""
] |
I have a table named 'resources'
```
Machine Host Enabled
mach1 host1 TRUE
mach2 host1 FALSE
mach3 host1 FALSE
mach4 host2 TRUE
mach5 host2 TRUE
```
I want to get the list of hosts where Enabled is True for all the resources/machines associated wi... | Try this:
```
SELECT Host
FROM resources
GROUP BY Host
HAVING COUNT(*) = COUNT(CASE WHEN Enabled = True THEN 1 END)
```
or:
```
SELECT DISTINCT Host
FROM resources AS r1
WHERE Enabled = TRUE AND
NOT EXISTS (SELECT 1
FROM resources AS r2
WHERE r1.Host = r2.Host AND... | TRY THIS ONE AND LET ME KNOW.
```
SELECT DISTINCT(Host)
FROM Resources
WHERE Enabled = TRUE AND Host NOT IN (Select Host FROM Resources WHERE Enabled = FALSE)
``` | SQL Query to get unique list | [
"",
"mysql",
"sql",
""
] |
Given a PostgreSQL table named `requests` with a column named `status` and a constraint like this:
```
ALTER TABLE requests ADD CONSTRAINT allowed_status_types
CHECK (status IN (
'pending', -- request has not been attempted
'success', -- request succeeded
'failure' -- request failed
));
```
In `psql`... | You can query the system catalog [`pg_constraint`](http://www.postgresql.org/docs/current/static/catalog-pg-constraint.html), e.g.:
```
select consrc
from pg_constraint
where conrelid = 'requests'::regclass
and consrc like '(status%';
consrc
-------... | ### Building on your design
To simplify things, I would provide allowed values as (100 % equivalent) **array literal** instead of the `IN` expression (that is converted into a clumsy ARRAY constructor):
```
ALTER TABLE requests ADD CONSTRAINT allowed_status_types
CHECK (status = ANY ('{pending, success, failure}'::... | PostgreSQL query for a list of allowed values in a constraint? | [
"",
"sql",
"database",
"postgresql",
"database-design",
"check-constraints",
""
] |
Given a table, for example **Article(Id,Body,Revisions)**, I would like to increment the Revisions attribute, and, once a certain limit is reached (it's a constant provided by the developer), an error should be thrown. Is this possible to achieve with a single UPDATE ... SET statement in T-SQL?
**What I've done:**
* ... | You could do this with a `WHERE` clause in your `UPDATE` statement, which would do the test. If the test fails, the update will not happen and your call with `context.Database.ExecuteSqlCommand` will return 0 instead of 1.
In case of a limit of 1000, the update SQL would be:
```
count = context.Database.ExecuteSqlCom... | Use a CHECK constraint. No update statement can violate bounds that are implemented by a CHECK constraint. Not even an update statement issued by a sleep-deprived DBA at the console.
```
create table article (
id integer primary key,
body nvarchar(max) not null,
-- Allow six versions. (Original plus five revi... | Specifying an upper bound for an int in UPDATE | [
"",
"sql",
"sql-server",
"entity-framework",
"t-sql",
""
] |
I was trying to access the time and timezone of a db. The query i had were :
```
select sysdate from dual
```
and
```
select systimestamp from dual
```
What would be the performance over-head of querying these ? I do understand that until 10g these were expensive and starting 11 they were to be in-memory. Would the... | I won't bother of that. Surely is fast.
An idea would be to measure it. Because is fast, let's do it 10000 times and measure the time:
```
declare
t number;
d date;
begin
t:=dbms_utility.get_time();
for k in 1..10000 loop
select sysdate into d from dual;
end loop;
dbms_output.put_line(dbms_utility.get_ti... | I stole @FlorinGhita's code and changed it to:
```
declare
t number;
d date;
begin
t := dbms_utility.get_time();
for k in 1..10000 loop
select sysdate into d from dual;
end loop;
dbms_output.put_line(dbms_utility.get_time() - t);
t := dbms_utility.get_time();
for k in 1..10000 loop
d := SYS... | Whats the performance of querying in dual on Oracle 11g | [
"",
"sql",
"oracle",
"select",
"oracle11g",
"oracle10g",
""
] |
I know that this is not possible to nest `insert ... exec` statements, but still I'm interested - is there a way to check if I already have active `insert ... exec` to avoid actual error?
So I want to have something like this:
```
....
if <check if I have outer insert into exec> = 0
insert into <#some temporary t... | A naive approach is to use `TRY/CATCH` block:
```
BEGIN
DECLARE @isNested BIT = 0;
BEGIN TRY
BEGIN TRANSACTION;
EXEC p2;
ROLLBACK; --COMMIT;
END TRY
BEGIN CATCH
-- Msg 8164 An INSERT EXEC statement cannot be nested.
IF ERROR_NUMBER() = 8164 SET @isNested = 1;
ROLLBACK;
END CATCH... | As stated [here](https://stackoverflow.com/a/3795413/2118383)
> This is a common issue when attempting to 'bubble' up data from a
> chain of stored procedures. A restriction in SQL Server is you can
> only have one INSERT-EXEC active at a time. I recommend looking at
> [How to Share Data Between Stored Procedures](htt... | Avoiding "An INSERT EXEC statement cannot be nested" | [
"",
"sql",
"sql-server",
"insert-into",
""
] |
This should be a simple one, but I have not found any solution:
The normal way is using an alias like this:
```
CASE WHEN ac_code='T' THEN 'time' ELSE 'purchase' END as alias
```
When using alias in conjunction with `UNION ALL` this causes problem because the alias is not treated the same way as the other columns.
... | 1. There is no alias in your presented query. You are confusing terms. This would be a [**column alias**](http://www.postgresql.org/docs/current/interactive/queries-table-expressions.html#QUERIES-TABLE-ALIASES):
```
CASE WHEN hr_subject='' THEN code_name ELSE hr_subject END AS ac_subject
```
2. In a [**`UNION` query*... | The CASE expression is supposed to return a value, e.g. 'time'.
Your value is another expression `subject ='time'` which is a boolean (true or false).
Is this on purpose? Does the other query you glue with UNION have a boolean in that place, too? Probably not, and this is what the DBMS complains about. | Assign a case value to a column rather than an alias | [
"",
"sql",
"postgresql",
"union",
"postgresql-9.1",
""
] |
I have a data table that essentially looks like this:
```
Employee ID ACTION Action DATE
1 SIC 12/10/15
1 CSL 11/10/15
2 SIC 12/10/15
2 CSL 11/10/15
1 CSL 10/22/15
2 CSL 10/22/15
1 SAC 1... | You may rather need an self-antijoin instead of self-innerjoin. Try it like this:
```
select *
from TableName A
where A.action = 'CSL'
and not exists (
select 1
from TableName B
where B.action in ('SIC','SAC')
and B.key_field = A.key_field
and A.action_dt between B.a... | Outer join the table to itself matching *unwanted* results, but filter out hits:
```
select A.*
from TableName A
left join TableName B on A.Action != B.Action
and A.Action_DT between B.Action_DT-7 and B.Action_DT+7
where A.Action = 'CSL'
and B.Action is null
```
A *successful* join means we *don't* want the row - w... | how can I select only rows that are not within a week of another type of row? | [
"",
"sql",
"oracle",
""
] |
I want to look at every row in `Examinations`, and for `Batra`, I want to update that column in `Patients` IF the value is 1 or 2.
A row for each patient already exists in `Patients`.
`Examinations`:
```
|ExaminationId | PatientId | Batra |
---------------------------------------
| 12345 | 123 | ... | Try something like this Query
```
UPDATE p
SET p.Batra = e.Batra
FROM Patients p
INNER JOIN Examinition e ON p.PatientId = e.PatientId
WHERE e.Batra IN (1,2)
``` | If I understand you correctly, you want something like this:
```
UPDATE
Patients
SET
Batra=em.batra
FROM
Patients AS p
INNER JOIN (
SELECT
e.patientid,
MAX(e.batra) AS batra
FROM
Examinations AS e
GROUP BY
e.patientid
) AS em O... | SQL Server join statement | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Imagine I have two simple tables, such as:
```
CREATE TABLE departments(dept INT PRIMARY KEY, name);
CREATE TABLE employees(id PRIMARY KEY, fname, gname,
dept INT REFERENCES departments(dept));
```
(simplified, of course).
I could have any of the following statements:
```
SELECT * FROM employees e INNER JOIN de... | > Now, apart from the fact that the first form has a duplicated column, is there a real advantage to the other two forms? Or are they just syntactic sugar?
**TL;DR** NATURAL JOIN is used in a certain style of relational programming that is simpler than the usual SQL style. (Although when embedded in SQL it is burdened... | `NATURAL JOIN` is not as widely supported and neither is `JOIN USING` (i.e. not in SQL Server)
There are many arguments for NATURAL JOIN being a bad idea. Personally I think that not explicitly naming things such as joins is inviting disaster.
For example if you add a column in a table without realising that it happe... | Inner Join vs Natural Join vs USING clause: are there any advantages? | [
"",
"sql",
"join",
""
] |
i try to get top 5 salary and second highest from employees table but it shows me also lowest salaries
check this picture salary column
[](https://i.stack.imgur.com/0dCzx.png)
and this is the output
[), that will really help you and your queries will become as simple as below:
For 2nd highest:
```
SELECT max(salary)
FROM employees
WHERE sa... | The reason you are not getting correct result is because you are saving `salary` as `string`. So `200` in `string` will be more than `1000` in `string`.
To compare 2 string, their characters are converted to `ascii` characters and then compared based on `ascii` characters. So `ascii` value of `2` in `200` is more than ... | lowest and highest salaries display | [
"",
"sql",
"sql-server",
"sql-server-2008",
"stored-procedures",
""
] |
I want to insert only one letter into the table field. What will be the data type that will accept only one character?
I don't want to use `VARCHAR(1)`, because it will truncate the remaining characters. I want that if the input is 1 character, it will insert otherwise it will not insert into the table | If you set the column length to be longer (for example, 255), then you can add a trigger which checks the length of the new field. If greater than 1 then you can trigger an error.
For a test example:-
```
CREATE TABLE IF NOT EXISTS `insert_test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`sometext` varchar(255) NOT ... | Have you tried the datatype:
```
TINYTEXT
```
?
or would it not work on the system you are using? | Datatype for 1 character only | [
"",
"mysql",
"sql",
""
] |
i'm using mysql, and i want to add some custom order for my select query.
For example i'm having this table name A, there are column 'a' and 'b'. And I can assure that 'b' is bigger than 'a'.
```
|a|b|
|3|4|
|1|9|
|2|7|
|6|9|
|8|9|
|2|6|
|4|8|
```
I want to select them out and order by value c = 5, the order rule is... | You can use `CASE` for this:
```
ORDER BY CASE WHEN @c < a AND @c < b THEN 1
WHEN a < @c AND @c < b THEN 2
WHEN @c > a AND @c > b THEN 3
END
``` | ```
Select a, b from (
Select a, b,
case when a>5 and b>5 then 1 when a<5 and b>5 then 2 when a<5 and b>5 then 3 end as weight
order by weight)w
``` | SQL - How to add this custom order for my select query? | [
"",
"mysql",
"sql",
""
] |
I have the table called Host in SQL as follows.
```
**FirstName** **LastName**
Krishna Krishna Murthy
Jithendra Jithendra Reddy
Varun Varun Kumar
Mahendra Varma
```
if firstname column is a part of LastName column I need to create one more column with values yes/No.
Output sho... | You can use
```
SELECT FirstName, LastName,
CASE WHEN LastName LIKE '%' + FirstName + '%'
THEN 'Yes' ELSE 'No'
END AS Flag
FROM host
```
to get the results you are looking for.
If you just want to search for cases where the forename is repeated, you might want to adjust the case to `LastName LIKE Firs... | You can use `like` for this. In standard SQL, this would look like:
```
select h.*,
(case when h.lastname like concat('%', h.firstname, '%')
then 'yes' else 'no'
end) as flag
from host h;
```
Note that most databases support operators for string concatenation, such as `||` or `+`. | Check to see if a column value is contained by another column | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
Is there anything equivalent to the `LIKE` we use with `varchar` that can be used with `int`?
I want to filter with three `parameters`, two of them are `varchar` so I can use `LIKE` and in case I get an empty string I still can retrieve all records. But how can I achieve similar thing with an `int`
I want to retrieve... | You could use this:
```
select * from Product
where Code like '%'+ @code +'%' AND name LIKE '%'+ @name +'%'
AND (@ptype IS NULL OR fkProductTypeID = @ptype)
```
if it's in a stored-procedure you should use an `IF ... ELSE`:
```
CREATE PROCEDURE dbo.SP_Name(@ptype int, @code varchar(1000), @name varchar(1000))
AS
B... | Is this what you want?
```
select *
from Product
where Code like '%'+ @code +'%' AND name LIKE '%'+ @name +'%' AND
(fkProductTypeID = @ptype or @ptype is null);
```
The value `''` doesn't make sense for an integer. And, don't mix types for comparisons. Just use `NULL` for this purpose. | SQL LIKE with int | [
"",
"sql",
"sql-server",
"wildcard",
""
] |
```
select *
from sometable
where column1='somevalue' and column2='someothervalue'
```
For the above query if both column1 and column2 have index tables ix1 and ix2, then which index is used for the above example? assume that 'somevalue' and 'someothervalue' are existing values in the table and column1 and column2 ha... | The index that is used is the one that the oracle optimizer believes is best for the query. "Best" in this case means the most selective -- that is, which single condition matches the fewest rows (estimated based on the statistics on the table).
For your query, the best index is either `sometable(column1, column2)` or... | Quite impossible to say, depending on many elements; for example:
```
create table someTable ( column1 number, column2 number);
create index someIndex1 on someTable(column1);
create index someIndex2 on someTable(column2);
insert into sometable values ( 1,10);
insert into sometable values ( 2,10);
insert into sometable... | Which index is used ? ORACLE DB SQL | [
"",
"sql",
"oracle",
""
] |
I have the following relations in my db:
**Organization:** information about political and economical organizations.
name: the full name of the organization
abbreviation: its abbreviation
**isMember:** memberships in political and economical organizations.
organization: the abbreviation of the organization
co... | I find the easiest way to handle this is by using `group by` and `having`. You just want to focus on the deserts, so the rest of the countries don't matter.
```
select m.organization
from isMember m join
geo_desert d
on m.country = d.country
group by m.organization
having count(distinct m.country) = (select ... | Word it like this: You are looking for organizations for which not exists a desert country they don't include.
```
select *
from organization o
where not exists
(
select country from geo_desert
except
select country from ismember
where organization = o.abbreviation
);
``` | SQL query that will retrieve set containing all entries from another set | [
"",
"sql",
"db2",
""
] |
Let's imagine I have a query like the following:
```
SELECT
CASE WHEN ONE = 1 THEN 1 ELSE 0 END,
CASE WHEN JUST_ONE = 1 THEN 1 ELSE 0 END,
CASE WHEN ANOTHER_ONE = 1 THEN 1 ELSE 0 END,
CASE WHEN TWO = 1 THEN 1 ELSE 0 END,
CASE WHEN JUST_TWO = 1 THEN 1 ELSE 0 END,
CASE WHEN ANOTHER_TWO = 1 THEN 1 ELSE 0 END... | Since they are different columns, you must explicitly mention them separately in the SELECT list. You cannot do it dynamically in pure **SQL**.
I would suggest, using a good **text editor**, it would hardly take a minute or two to write the entire SQL.
You could use **DECODE** which will have some less syntax instead... | Below is an example of dynamically creating query. You can put this in e.g. cursor variable if you want more queries created.
```
select 'SELECT ' || listagg('CASE WHEN '||column_name||' = 1 THEN 1 ELSE 0 END ' || column_name,',') within group(order by column_name) || ' FROM YOUR_TABLE_NAME'
from cols
where data_type... | Metaprogramming oracle sql select statement | [
"",
"sql",
"oracle",
""
] |
I have a group of machines. They run and stop occasionally. These run times are recorded into a postgres table automatically with timestamps `starttime` and `endtime`.
I need to find the run time per machine in a 6 hour period. This is what I have so far:
```
SELECT machine, SUM(EXTRACT(EPOCH FROM (endtime - starttim... | EDIT : this is what you need.
When it start between the range, and ends after, it will calc it as ended at 18:00:00.
Same goes for when ended between the range and start before, it will calc as it started at 12:00:00
```
SELECT machine, SUM(EXTRACT(EPOCH FROM (endtime - starttime)))
FROM (SELECT machine,
... | You can use the overlaps operator:
```
SELECT machine, SUM(EXTRACT(EPOCH FROM (endtime - starttime)))
FROM table
where (starttime, endtime) overlaps (timestamp '2016-01-27 12:00:00', timestamp '2016-01-27 18:00:00')
GROUP BY machine
ORDER BY machine
``` | SQL solution to overlapping timeframes | [
"",
"sql",
"postgresql",
""
] |
How do I insert a record in a column having CLOB data type(so big text) having single quote in it?
I've already seen
[How to handle a single quote in Oracle SQL](https://stackoverflow.com/questions/2875257/how-to-handle-a-single-quote-in-oracle-sql)
but the solution is make it manual and I'm trying to insert Long te... | Try with the [Q'](https://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements003.htm) operator; for example:
```
create table t_clob ( a clob)
insert into t_clob values (q'[START aa'a''aa aa 'a'' aa'a' a'a' a END]')
``` | You can use quoted notation:
`SELECT q'|text'containing'quotes|' FROM DUAL`
The pipes can be replaced by any matching symbol. It must be the same symbol at the beginning and at the end except when parentheses are used, then `()`, `[]` or `{}`.
See <https://docs.oracle.com/database/121/SQLRF/sql_elements003.htm#SQLRF... | How to handle a single quote in Oracle SQL with long text | [
"",
"sql",
"oracle",
""
] |
I'm trying to extract the total number of website hits plus the rate of change(rate of increase/decrease) per client per city per day as a percentage in a single SQL query but not able to get it right.
I've created an example at
> [http://www.sqlfiddle.com/#!9/fd279/8](http://www.sqlfiddle.com/#!9/fd279/8 "Rate of ch... | To get percentage based increase/decrease
```
select
t1.HitDate,
t1.City,
t1.Client,
SUM(t1.NumVisits),
IFNULL(((SUM(t1.NumVisits) - IFNULL((SELECT SUM(t2.NumVisits) FROM PAGE_HITS t2 WHERE t2.HitDate = t1.HitDate-1 AND t2.City = t1.City AND t2.Client = t1.Client), 0)) * 100) / IFNULL((SELECT SUM(t2.Nu... | Try avoiding inner join, it has wrong condition anyway (`t1.hitDate = t2.hitDate and t1.hitDate-1 = t2.hitDate` which can't be satisfied):
```
select
t1.HitDate,
t1.City,
t1.Client,
SUM(t1.NumVisits) - IFNULL((SELECT SUM(t2.NumVisits) FROM PAGE_HITS t2 WHERE t2.HitDate = t1.HitDate-1 AND t2.City = t1.City ... | MySQL - Total count & rate of change in a single SQL query | [
"",
"mysql",
"sql",
""
] |
For testing / debugging purposes, I need to get an enormous string into a field for one of my records. Doesn't matter what the string is. Could be a million "\*"s or the contents of Moby Dick.... whatever.
I'm not able to save a string so large via the app's UI because it crashes the browser. I'd like to write an SQL ... | You can use the `repeat()` function; quoting from the [Postgres *String Functions and Operators* documentation](https://www.postgresql.org/docs/current/functions-string.html):
> Function: `repeat(string text, number int)`
> Return Type: `text`
> Description: Repeat *string* the specified *number* of times
```
tes... | Create your own lipsum function.
```
create or replace function lipsum( quantity_ integer ) returns character varying
language plpgsql
as $$
declare
words_ text[];
returnValue_ text := '';
random_ integer;
ind_ integer;
begin
words_ := array['lorem', 'ipsum', 'dolor', '... | How to create a huge string in Postgresql | [
"",
"sql",
"string",
"postgresql",
""
] |
what is the correct way to do a bulk insertOrUpdate in Slick 3.0?
I am using MySQL where the appropriate query would be
```
INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6)
ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);
```
[MySQL bulk INSERT or UPDATE](https://stackoverflow.com/questions/6286452/mysql-bulk-insert-o... | There are several ways that you can make this code faster (each one *should* be faster than the preceding ones, but it gets progressively less idiomatic-slick):
* Run `insertOrUpdateAll` instead of `insertOrUpdate` if on slick-pg 0.16.1+
```
await(run(TableQuery[FooTable].insertOrUpdateAll rows)).sum
```
* Run ... | As you can see at [Slick examples](http://slick.typesafe.com/doc/3.1.1/gettingstarted.html#populating-the-database), you can use `++=` function to insert using JDBC batch insert feature. Per instance:
```
val foos = TableQuery[FooTable]
val rows: Seq[Foo] = ...
foos ++= rows // here slick will use batch insert
```
Yo... | Slick 3.0 bulk insert or update (upsert) | [
"",
"mysql",
"sql",
"scala",
"slick",
"typesafe",
""
] |
I'm trying to pull back multiple different sums from one table using different criteria. The only problem is that my subqueries were pulling back more than one response, so I changed my query a bit and then got extremely lost trying to find the best way to do this.
Here's the query I'm working with right now:
```
... | The reason you are not getting your expected results, is because there is no relationship between your subqueries and the table in your FROM. You would need to add that relationship in each of your subqueries `WHERE` clauses (which is called a Correlated Subquery since it uses values from the outer query in the subquer... | Use case statements instead of selects
```
SELECT TER_ID AS TER_ID,
SUM(MED_AMT) AS NET_SLS_AMT,
SUM(CASE WHEN TND_CD = 1 THEN MED_AMT
ELSE 0
END) AS CASH_AMT,
SUM(CASE WHEN DAY_TER_MEDIA.TND_CD IN (4,5,16,18,23,31) THEN MED_AMT
ELSE 0
E... | Multiple Subqueries on the Same Column | [
"",
"sql",
"sql-server",
""
] |
I've wanted to create a view in my sql but I've been getting this error:
> Duplicate column name 'product\_id'
Here's my query:
```
CREATE VIEW product_view AS
SELECT
*
FROM
products
JOIN storeitems on products.product_id = storeitems.product_id;
```
I believe creating an alias would solve the problem ... | You get the error because both tables in your query has a column named product\_name and selected column names must be unique.
You make your aliases like this:
```
CREATE VIEW product_view AS SELECT p.product_name, si.product_name StoreItemsProductName -- continue with what you want to select...
FROM products p JOIN ... | yes, creating an column alias would solve the problem and you do it like
```
select column1 as test_column
```
But if this your original query then I doubt you won't get this error since you are selecting from single table called `products` and obviously same table won't have multiple column with same name.
Anyway y... | Duplicate column name in SQL | [
"",
"sql",
"alias",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.