Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I am trying to run a series of checks on TextBox1 and display error messages when conditions are not met. Ultimately when all conditions are met before I then do a table insert and open a file dialog.
The first statement is to check if there is a value
The second checks that no numbers have been used
The third check... | ```
Dim tarrif As String = cmd.ExecuteScalar().ToString()
```
The problem is if no result is returned, then `cmd.ExecuteScalar()` will return `Nothing` and `cmd.ExecuteScalar().ToString()` will throw an exception.
A better option is:
```
cmd.CommandText = "SELECT 1 FROM Tarrifs WHERE Tarrif = @Tarrif"
cmd.Parameters... | The query will return Null I think if @tariff does not match any values on the table. This might be the problem. Just a guess - haven't tested. Maybe just change the query to
```
SELECT isNull(TarrifId,0) FROM Tarrifs WHERE Tarrif = @Tarrif
``` | Object reference error when checking if value existi in SQL dB | [
"",
"sql",
"vb.net",
""
] |
Table 1
```
Column1 Column2 Column 3
A Null 12
B Null 15
C 0 15
```
Table 2
```
Column2 Column3
0 15
0 12
```
I have table 1 and Table 2 , Here I'm passing table 2 parameters to table 1 which should return the column1 but it sho... | You could do this as a union:
```
select Column1 from
(
select Table1.Column1 as Column1,Table1.Column2 as Column2
from Table1
join Table2 on
Table1.Column2=Table2.Column2 and Table1.Column3=Table2.Column3
UNION
select Table1.Column1 as Column1,Table1.Column2 as Column2
from Table1
join Table2 on
Table1.Column2 is... | ```
SELECT t1.* FROM table1 t1
INNER JOIN table2 t2
ON NVL(t1.column2,0) = t2.column2 and t1.column3 = t2.column3
``` | SQL - Null value should match with not null value with another table | [
"",
"sql",
""
] |
Help me explain what is this question meant.
"Find all combination of employee names and department names."
For my table
```
//EMPLOYEE
E# ENAME DNAME
-----------------------------
1 JOHN IT
2 MAY SCIENCE
3 SITI SCIENCE
//DEPARTMENT
DNAME
------------
RESE... | Its a bit unclear, but to find all combinations you would create a [Cartesian product.](http://en.wikipedia.org/wiki/Cartesian_product)
```
select
e.ename, d.dname
from
employee e,
dname d
```
Oracle supports the above sql and uses [`CROSS JOIN`](http://docs.oracle.com/javadb/10.8.2.2/ref/rrefsqljcrossjoin.html... | My understanding is they want you to create a cartesian:
```
select
EMPLOYEE.ENAME
,DEPARTMENT.DNAME
FROM EMPLOYEE, DEPARTMENT
``` | SELECT clause with condition | [
"",
"sql",
"oracle",
""
] |
The database is updated by executing a list of queries that are located in a folder.
I need to be able to detect *any* errors that would also result in "Query completed with errors" in SQL Server Management Studio.
The following works to detect the "Invalid Object" error:
```
PS SQLSERVER:\> $ErrorActionPreference
S... | Regardless of the ErrorAction setting, invoke-sqlcmd cmdlet has a bug present in SQL Server 2008, 2008 R2 and 2012 versions of the cmdlet where T-SQL errors like divide by 0 do not cause an error. I logged a connect item on this and you can see details here:
<https://connect.microsoft.com/SQLServer/feedback/details/77... | You are ignoring erros by using `-ErrorAction SilentlyContinue`, change that to `-ErrorAction Stop`.
**Edit:**
Turns out if you want error handling don't use `Invoke-SqlCmd` (<http://blogs.technet.com/b/heyscriptingguy/archive/2013/05/06/10-tips-for-the-sql-server-powershell-scripter.aspx>)
You can use `GenericSqlQu... | Error detection from Powershell Invoke-Sqlcmd not always working? | [
"",
"sql",
"powershell",
"error-handling",
""
] |
I'm using a mysql database, and I have the next query:
```
SELECT DISTINCT OP1.meta_value AS meta_value
FROM wp_postmeta OP1 WHERE OP1.meta_key like 'size'
and OP1.meta_value is not null and OP1.meta_value <> 'null'
ORDER BY OP1.meta_value DESC
```
The results are: small, medium, huge, big,
I need to order this ... | You can do it with the [FIELD](http://dev.mysql.com/doc/refman/5.6/en/string-functions.html#function_field) function
```
SELECT DISTINCT
OP1.meta_value AS meta_value
FROM
wp_postmeta OP1
WHERE OP1.meta_key like 'size'
and OP1.meta_value is not null
and OP1.meta_value <> 'null'
ORDER BY FIELD (met... | ```
SELECT DISTINCT OP1.meta_value AS meta_value FROM
wp_postmeta OP1 WHERE OP1.meta_key like 'size'
and OP1.meta_value is not null
and OP1.meta_value <> 'null'
ORDER BY (CASE
WHEN meta_value='small' THEN 1
WHEN meta_value='medium' THEN 2
WHEN meta_value='big' THEN 3
WHEN meta_value='hude' THE... | Order an SQL Query by literal | [
"",
"mysql",
"sql",
""
] |
I've inherited a poorly set-up data source. Given the current data structure of:
```
PreAddress City County
12312 Osprey Drive NW Gig Harbor NULL NULL
12312 Osprey Drive NW Gig Harbor NULL NULL
3022 SW Bradford St Seattle ... | You'd need to have a lookup table of the possible table names. Off the top of my head, maybe something like:
```
UPDATE Address SET
PreAddress=Replace(a.PreAddress,b.City,''),
City=b.City
FROM Address a INNER JOIN Cities b ON b.City=RIGHT(a.PreAddress,LEN(b.city))
``` | If this is a once off update as opposed to a regular fix-up, for an alternative to SQL you use a batch geocoding service that will format the address's, and you could load them back into the table. You'd get co-ordinates that way too :). | SQL Copy part of a column into a new column | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Using Sequel Pro, I have these two tables:
```
Table1
Name Year x y
John Smith 2010 10 12
Adam Jones 2010 8 13
John Smith 2011 7 15
Adam Jones 2011 9 14
etc.
```
and
```
Table2
Name Year z
Smith John Smith John 2010 27
Jones Adam Jon... | A bit of an odd data model aside, you've turned the tables around in the `LIKE` part (table1.name should be a part of table2.name, not the other way around), and you need to add the percents to the *value*, not the *name* of the field, that means not quoting the name;
```
SELECT table1.*, table2.z
FROM table1
INNER JO... | Your query is incorrect, you are saying that the content of the column should be like `abcdTable2.Nameefgh`. This would be correct:
```
Select Table1.*, Table2.z
From Table1
Inner join Table2
On Table1.Name like "%" + Table2.Name+ "%" and Table1.Year=Table2.Year
```
This query will be quite slow for bigger table, but... | "Like" operator in inner join in SQL | [
"",
"sql",
"join",
"sql-like",
""
] |
I'm trying to write a query to produce a dataset from two or more tables, and I'm having trouble writing the query. I apologize in advanced my lack of knowledge in SQL.
Table 1 consists of basic customer account info and Table 2 consists of customer contract details where one customer account can have multiple contrac... | select acct\_id
from table1
where acct\_status = "active" and
acct\_id not in (select acct\_id from table2 where contract\_status = "active") | ```
SELECT A.*
FROM Table1 A
WHERE A.acct_status = 'active'
AND NOT A.acct_id in (SELECT acct_id FROM Table2 WHERE contract_status = 'active')
``` | Query Results from Two Different Tables | [
"",
"sql",
"select",
"join",
""
] |
Hi I have a column with number datatype
the data like **1310112000** this is a date, but I don't know how to make it in an understandable format:
ex: 10-mar-2013 12:00:00 pm
Can any one please help me. | That is EPOCH time: number of seconds since Epoch(1970-01-01). Use this:
```
SELECT CAST(DATE '1970-01-01' + ( 1 / 24 / 60 / 60 ) * '1310112003' AS TIMESTAMP) FROM DUAL;
```
Result:
```
08-JUL-11 08.00.03.000000000 AM
``` | Please try
```
select from_unixtime(floor(EPOCH_TIMESTAMP/1000)) from table;
```
This will give the result like E.g: 2018-03-22 07:10:45
PFB refence from [MYSQL](https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_from-unixtime) | How to convert Epoch time to date? | [
"",
"sql",
"oracle11g",
"unix-timestamp",
""
] |
I'm currently trying to teach myself SQL in order to write better reports with our Orion system and I'm running into a small issue. I want to generate a report with a count of the number of Windows machines and Linux machines. This is my current code.
```
SELECT OperatingSystem, Count(OperatingSystem) AS TotalMachi... | to solve such problems I prefer to use `union` neither `case`, as it helps you easily extend query in future:
```
select OSType, count(*) as TotalMachines
from (
SELECT 'Linux' as OSType FROM Machines WHERE OperatingSystem LIKE '%Linux%'
UNION ALL
SELECT 'Windows' as OSType FROM Machines WHERE OperatingSys... | Yes. You want to use `case` in the `group by` clause itself:
```
SELECT (case when OperatingSystem LIKE '%Windows%' then 'Windows'
when OperatingSystem LIKE '%Linux%' then 'Linux'
end) as WhichOs, Count(*) AS TotalMachines
FROM Machines
Where (OperatingSystem LIKE '%Windows%') OR
(OperatingSy... | Combine SQL Count Results | [
"",
"sql",
""
] |
Could anyone give me an idea how to fetch last 50 (or last n records ) when the table is in Ascending Order.? | I know this post is old but had to share this solution.
I struggled with this for some time as well but at midnight today, it hit me like a rock. The below works for SQL Server and has a very fast return time. It returns the records in ASC order.
```
SELECT * FROM table1
WHERE column1 in (
SELECT TOP(50) column1... | You can use - limit or TOP to solve it .
With limit -
```
SELECT col1,col2,.. from table_name ORDER BY col_name DESC limit 50
```
with top -
```
SELECT TOP 50 col1,col2,.. from table_name ORDER BY col_name DESC
``` | SQL Table in Ascending Order + Get Last 50 Records | [
"",
"sql",
""
] |
I have a not-that-large database that I'm trying to migrate to SQL Azure, about 1.6 gigs. I have the BACPAC file in blob storage, start the import, and then... nothing. It gets to 5% as far as the status goes, but otherwise goes nowhere fast. After 10 hours, the database size appears to be 380 MB, and the monitoring sh... | Ugh, I hate answering my own question, but I figured out what the issue is. It appears to have to do with their new basic-standard-premium tiers (announced April 2014). The database imports to the old web-business levels no problem. Because the new tiers are built around throttling for "predictable performance," they m... | I've yet to try this myself (spent 5 hours so far today waiting for a ~11GB Test database to import to an S3 sized Azure SQL database)...
But MS themselves mention that is due to them not assigning enough hamsters to run the wheel, and suggest using SQLPackage.exe direct from the command line as a workaround for slow ... | SQL Azure import slow, hangs, but local import takes 3 minutes | [
"",
"sql",
"sql-server",
"azure",
""
] |
I have the following results in employee table :
```
ID | Name | Number
---------------------
1 | Dani | 15
2 | Dani | 20
3 | Yara | 10
```
I need to write sql query to get the following result:
```
ID | Name | Number
------------------
2 | Dani | 20
3 | Yara | 10
```
as you see , if the resul... | Since you also want the correct id pointing to the maximum value, this is the easiest way:
```
WITH TT AS (
SELECT ID, Name, Number, rank() OVER(PARTITION BY Name ORDER BY Number DESC) R
FROM employee
)
SELECT ID, Name, Number
FROM TT
WHERE R = 1;
```
It should work correctly on Oracle and SQL Server as they ... | From the data set you provided you could simply use a `GROUP BY` clause. The syntax in the various engines you mentioned are all pretty similar.
In MySQL:
```
SELECT MAX(`ID`), `Name`, MAX(`Number`)
FROM `Employee`
GROUP BY `Name`
```
In T-SQL (SQL Server):
```
SELECT MAX([ID]), [Name], MAX([Number])
FROM [Employee... | Get the max values from list result | [
"",
"sql",
"sql-server",
"oracle",
""
] |
I have a similar issue to this [No duplicates in SQL query](https://stackoverflow.com/questions/1543435/no-duplicates-in-sql-query)
Please [find here the sqlFiddle](http://sqlfiddle.com/#!3/99ea1/1)
I have this:
```
+----------+-----------------+----------+----------+-----------+----------+
| TAFIELDA | DESCRIPTIO... | **Using Sub-Query**
```
SELECT * FROM
(
SELECT *
,ROW_NUMBER() OVER (PARTITION BY DOCNUMBER ORDER BY tAFieldA DESC) rn
FROM TABLEA A
INNER JOIN TABLEB B ON A.TAFIELDA = B.TBFIELDB
INNER JOIN TABLEC C ON B.tBFieldA = C.tCFieldB
) Sub
WHERE rn = 1
```
**Using CTE**
```
;WITH CTE
AS
(
SELECT *
... | Use a sub query:
```
SELECT *
FROM TABLEA A
INNER JOIN TABLEB B ON A.TAFIELDA = B.TBFIELDB
INNER JOIN TABLEC C ON B.tBFieldA = C.tCFieldB
WHERE TAFIELDA IN (
SELECT max(tAFieldA)
FROM TABLEA A
INNER JOIN TABLEB B ON A.TAFIELDA = B.TBFIELDB
INNER JOIN TABLEC C ON B.tBFieldA = C.tCFieldB
WHERE DocNumber =... | Removing duplicates with Group By | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
Table `Movie(Title,year,director,length)`
Find movies whose titles appears more than once (different years)
```
Select Distinct title
From Movie as x
where year <> any
(Select year
from movie
where title = x.title);
```
I don't understand this sql code, anyone can explai... | [From the docs](http://www.postgresql.org/docs/current/interactive/functions-comparisons.html#AEN18030):
**9.23.3. ANY/SOME (array)**
> expression operator ANY (array expression)
> expression operator SOME (array expression)
>
> The right-hand side is a parenthesized expression, which must yield an array value. The l... | Let's talk about `where year <> any`:
The sub query will get you all years one title appears. For every row (`title`), check if there is **any other** year(s) that title appears which is different `<>` from current year.
1. If TRUE, that title appears more than once (in different years). Return that title.
2. If FALS... | Correlated sub query of movie | [
"",
"sql",
""
] |
Generally speaking I need to search `varchar(100)` column for the pattern `'%bA%'`, where
* `A` - uppercase non-ascii character and
* `b` - lowercase non-ascii
character.
From the high level perspective I need to find all strings where **[space]** symbol is missed before the uppercase character, for example as a re... | If it really is just "firstname and lastname columns concatenation without a space between" then this may suffice:
```
select
*
from mytable
where LEN(ConcatenatedName) <> LEN(REPLACE(ConcatenatedName, ' ', ''));
```
You can substitute whatever passes for a space in your local environment, of course. If there are... | You can use the basic pattern recognition of the `LIKE` operator.
The most used capability is the `%`, but it recognize set search with `[set]`.
The pattern you search is
```
WHERE column LIKE '%[^ ][A-Z]%'
```
Where the character `^` is used to negate the following pattern.
**EDIT**
Checking the comment from ... | SQL Server: How to find position of the first uppercase non-ascii character in the string? | [
"",
"sql",
"sql-server",
"t-sql",
"non-ascii-characters",
""
] |
I have mysql dump called `dbBACKUP.sql` about 152 MB. It has thousands of records. I use the following command to import it:
```
mysql -u root -p --default-character-set=utf8 phpbb3 < dbBACKUP.sql
```
After supplying the password of the root, I go to phpmyadmin to check the data imported to the database. I notice slo... | I did a google search and found this blog that might help you: <http://cmanios.wordpress.com/2013/03/19/import-a-large-sql-dump-file-to-a-mysql-database-from-command-line/>
```
-- connect to database
mysql -u root -p
-- set network buffer length to a large byte number.
set global net_buffer_length=1048576;
-- set ma... | Try to use SOURCE command instead of redirecting your sql file.
```
mysql -u root -p --default-character-set=utf8
use phpbb3
source /full/path/to/your/dbBACKUP.sql
``` | Large mysql dump failed to be imported | [
"",
"mysql",
"sql",
"windows",
"import",
""
] |
I have following query -
```
UPDATE THINGS
SET Col 1 = CASE when 'A' then 'APPLE'
when 'B' then 'BALL'
when 'C' then 'CARROT'
else NULL
end,
Col 2 = Case Col 1 when 'APPLE' then 'FRUIT'
when 'BALL' then 'TOY'
... | You can use this approach by using variable to store data and then use it foe next column.
```
DECLARE @val VARCHAR(20) -- type of Col1
UPDATE THINGS
SET @val = [Col 1] = CASE WHEN 'A' THEN 'APPLE'
WHEN 'B' THEN 'BALL'
WHEN 'C' THEN 'CARROT'
END,... | You can't rely upon the order of execution of assignments in a query. Most likely, the DBMS will pull the row, check the values, then write the changes. In SQL Server, I'd write it like this:
```
UPDATE THINGS
SET [Col 1] = CASE WHEN [Col 1] = 'A' then 'APPLE'
WHEN [Col 1] = 'B' then 'BALL'
W... | Does UPDATE happen column by column in SQL Server | [
"",
"sql",
"sql-server",
"sql-update",
"case",
""
] |
I want select children of category and count of theirs children.
Structure of **Category**:
```
Id Parent Name
0 0 main
1 0 Games
2 0 Books
3 2 Drama
4 2 Comedy
```
For id '0' it should return games 0, books 2. For id '2' it should return drama 0, comedy 0
How to do i... | ```
Id Parent Name
1 0 main
2 1 Games
3 1 Books
4 3 Drama
5 3 Comedy
```
If you add '0' value for the Main Row you can do this using a Simple Query. Main is a Parent of Book and Games so we had to use some other value for Main.
So After that you need to write a Simple Q... | Use inner join to fetch the data :
```
SELECT c.Name, c.Parent
FROM Category c
INNER JOIN Category p on c.id = p.parent
``` | SQL: Select children and number of their children | [
"",
"mysql",
"sql",
""
] |
I have a SQL Server table with a nvarchar(50) column. This column must be unique and can't be the PK, since another column is the PK. So I have set a non-clustered unique index on this column.
During a large amount of insert statements in a serializable transaction, I want to perform select queries based on this colum... | After all, mystery solved! Rather stupid situation I guess..
The problem was in the select statement. The where clause was missing the quotes, but due to a devilish coincidence of the existing data were only numbers, the select wasn't failing but just wasn't executing until the inserts committed. When the first alphan... | First, you can change the PK to be a non-clustered index, then you you could create a clustered index on this field. Of course, that may be a bad idea based on your usage, or just simply not help.
You might have a use case for a covering index, see previous [question re: covering index](https://stackoverflow.com/quest... | SQL Server unique index on nvarchar issue | [
"",
"sql",
"sql-server",
"nvarchar",
"unique-index",
""
] |
I need to run a SQL Server query that either "gets" or "creates" a record. Pretty simple, but I am not sure if this will create any race conditions.
I have read a few articles regarding locking during insert/updates e.g. <http://weblogs.sqlteam.com/dang/archive/2007/10/28/Conditional-INSERTUPDATE-Race-Condition.aspx>,... | GET occurs far more frequently than CREATE, so it makes sense to optimize for that.
```
IF EXISTS (SELECT * FROM MyTable WHERE Id=@Id)
SELECT Id, X, Y, Z FROM MyTable WHERE Id=@Id
ELSE
BEGIN
BEGIN TRAN
IF NOT EXISTS (SELECT * FROM MyTable WITH (HOLDLOCK, UPDLOCK) WHERE Id=@Id )
BEGIN
--... | Your code definitely has race conditions.
One approach is to merge the conditions into one `insert`, but I'm not 100% sure that this protects against all race conditions, but this might work:
```
INSERT INTO Table(Id, X, Y, Z)
SELECT @Id, @X, @Y, @Z
WHERE NOT EXISTS (SELECT 1 FROM Table WHERE ID = @ID);
SELE... | SQL Server 2012 potential race condition on select or insert | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I have a SQL query (in MySQL) that select a total and a count of how many completed task have the table:
```
SELECT
count(*) as total, IF(SUM(NOT `completed`) IS NULL,0,SUM(NOT `completed`)) as incomplete
FROM
tasks
```
The table can be made something like:
```
CREATE TABLE `tasks` (
`clave` int(11) NOT NULL A... | this may be a better way to do it because you do less calculations for **performance**
using the schema richard posted - see [FIDDLE](http://sqlfiddle.com/#!2/c2e74b/5)
```
SELECT
total,
num_complete,
total - num_complete as num_incomplete
FROM(
SELECT
COUNT(*) as total,
SUM(IF(t.co... | The efficiency (or lack thereof) will have more to do with the indices present on the table, as well as the storage engine itself. Likewise, whether or not the result is stored in cache will have more to do with the storage engine than with the statement you are writing.
If I were writing this on an INNODB-based stora... | Performance of a duplicate agregate function in a select query | [
"",
"mysql",
"sql",
"performance",
""
] |
I would like to know, if there is any possible way in SQL to distinguish which one of default parameters was set when function was called?
F.e. if there is function:
```
CREATE OR REPLACE FUNCTION someFunction (
ID NUMBER,
showNames VARCHAR2 DEFAULT 'N',
showAddress VARCHAR2 DEFAULT 'N')
```
and it will be called lik... | if you use Oracle database you could specify exact param name:
```
someFunction(123, showAddress =>'Y')
``` | Since this is tagged as `Oracle`; you can use named parameter like `formal => actual`. So in your case, you can say `someFunction(123, shownames => 'Y')` in which case ID and shownames will be set; whereas showaddress will have default value.
Otherwise, it's all positional parameter and hence calling `someFunction(123... | SQL function with multiple default parameters | [
"",
"sql",
"oracle",
""
] |
I tried a lot allready, but im not getting the result that i want.
Lets say i got the following data in the first table:
```
ColA ColB ColC ColD
AA 11 1 50€
AA 11 1 60€
AA 11 1 10€
BB 22 1 15#
```
And in Table B I have this:
```
ColA ColB ColC ColD
AA 11 ... | Try this:
```
SELECT A.ColA,
A.ColB,
A.ColC,
A.ColD,
B.Cold AS ColE
FROM Table_A AS A
JOIN Table_B AS B
ON B.ColA = A.ColA
AND B.ColB = A.ColB
GROUP BY A.ColA,
A.ColB,
A.ColC,
A.ColD,
B.Cold
``` | Try this;
```
SELECT A.ColA,A.ColB,A.ColC,A.ColD,B.ColD as BCol
FROM TableA A JOIN
TableB B ON A.ColA=B.ColA AND A.ColB=B.ColB AND A.ColC=B.ColC
GROUP BY A.ColA,A.ColB,A.ColC,A.ColD,B.ColD
```
Result:
```
COLA COLB COLC COLD BCOL
AA 11 1 10€ Delta
AA 11 1 50€ ... | Join two tables without extra rowes | [
"",
"sql",
"join",
"sql-server-2012",
""
] |
I am trying to get the difference between below 2 queries
**Query 1:**
In which I have given condition **'Orders.OrderID != null'** in on clause
```
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON (Customers.CustomerID=Orders.CustomerID and Orders.OrderID is not null)
```
**Query 2:... | The difference in that in query 1, Orders.OrderID != null (or Orders.OrderId is not null) is being used to filter the rows in the Orders table and in query2, it is being used to filter the rows in the result set. | Change the `!= NULL` to `IS NOT NULL` | SQL Query: difference in condition in On clause and where clause | [
"",
"mysql",
"sql",
"left-join",
"where-clause",
""
] |
***UPDATE NO 2***
With very important inputs from Solution 1 and Solution 2, I finally have a sql that does exactly what it needs to. Thanks to both users, appreciate their assistance. I wish I could mark both solution as answers, but considering the base of my query is from @papo's solution and also that it is very s... | Only show the SHIPPING row when there are uncompleted items for this order. Show the other items only when they are not completed.
```
SELECT OrderNo, ItemCode, Status
FROM table1 t1
WHERE ((ItemCode = 'SHIPPING'
AND EXISTS (SELECT * FROM table1
WHERE OrderNo = t1.OrderNo
AND Status != 'Completed... | One option is to use an EXISTS predicate to test whether there are any rows (other than 'SHIPPING') that aren't status 'COMPLETED' to conditionally return the 'SHIPPING' row.
For example:
```
SELECT t.ItemCode
, t.Status
FROM mytable t
WHERE t.OrderNumber = 111
AND ( ( t.ItemCode <> 'SHIPPING' AND t.Stat... | SQL query to include/exclude an item line based on the status of other lines in the order | [
"",
"sql",
"sql-server",
""
] |
in sql server basically I have a query to find duplicates in one table. I want to filter this list down to all the duplicates that appear in the one table and are not contained in the second table
to get duplicates:
```
select [OBId], COUNT(*) AS dupes
FROM [Broker] b
GROUP BY [OBId]
HAVING (CO... | what if you simply use a subquery and say this
```
select [OBId],
COUNT(*) AS dupes
FROM [Broker] b
WHERE [OBId] NOT IN (select other_table_id from other_table)
GROUP BY [OBId]
HAVING (COUNT(*) > 1)
``` | You could do it with a NOT EXISTS in a subquery:
```
SELECT sub.*
FROM
(SELECT [OBId]
, COUNT(*) AS dupes
FROM [Broker] b
GROUP BY [OBId]
HAVING COUNT(*) > 1) sub
WHERE NOT EXISTS
(SELECT 1
FROM SomeSecondTable sst
WHERE sub.OBId = BrokerId);
```
If you are trying to return th... | sql show duplicate rows missing from another table | [
"",
"sql",
"sql-server-2008",
""
] |
Does anyone know how to split words starting with capital letters from a string?
Example:
```
DECLARE @var1 varchar(100) = 'OneTwoThreeFour'
DECLARE @var2 varchar(100) = 'OneTwoThreeFourFive'
DECLARE @var3 varchar(100) = 'One'
SELECT @var1 as Col1, <?> as Col2
SELECT @var2 as Col1, <?> as Col2
... | Here is a function I created that is similar to the "removing non-alphabetic characters". [How to strip all non-alphabetic characters from string in SQL Server?](https://stackoverflow.com/questions/1007697/how-to-strip-all-non-alphabetic-characters-from-string-in-sql-server/1008566#1008566)
This one uses a case sensit... | Here is a function I have just created.
**FUNCTION**
```
CREATE FUNCTION dbo.Split_On_Upper_Case
(
@String VARCHAR(4000)
)
RETURNS VARCHAR(4000)
AS
BEGIN
DECLARE @Char CHAR(1);
DECLARE @i INT = 0;
DECLARE @OutString VARCHAR(4000) = '';
WHILE (@i <= LEN(@String))
BEGIN
SELECT @Char = SUBSTRING(@String... | Split words with a capital letter in sql | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have 5 tables and columns pertinent to this query:
* Dogs (ID, CallName, Color, Sex, Chipnumber, BreedID)
* Breed (ID, Name)
* Status (ID, Status, OwnedOnPremises)
* DogsStatus (ID, DogsID, StatusID, StatusDate, Note, ContactsID)
* Contacts (ID, Name)
I am wanting a result of all dogs and their LATEST status. For a... | You'll need to join your `MaxStatusDate` to the `DogsStatus` table. That way you will only get the most recent status, in the case where you have multiple statuses.
Something like
```
SELECT
d.CallName, b.Name AS 'Breed', d.Color, d.Sex, d.ChipNumber
FROM
Dogs d
innner join DogsStatus ds
ON d.dogsid = ds.d... | You're close. You just need to go back to the DogStatus table to get that full record. Note that I prefer CTEs for this, but your existing derived table (subquery) approach works just fine, too:
```
With StatusDates As
(
SELECT
DogsID, MAX(StatusDate) as StatusDate
FROM DogsStatus
GROUP BY Dogs... | SQL Query return latest date with additional information from tables | [
"",
"sql",
"sql-server",
""
] |
Given a column containing ngrams in a `VARCHAR` with `utf8mb4_unicode_ci` collation:
```
+---------------------------+
| ngram |
+---------------------------+
| stack overflow |
| stack |
| overflow |
| stack overflow protection |
| overflow protectio... | If I understand your logic correctly, this query should give you the correct result:
```
SELECT n1.ngram
FROM
ngrams n1 LEFT JOIN ngrams n2
ON
n2.ngram IN ('stack', 'stack overflow', 'protection')
AND n2.ngram LIKE CONCAT('%', n1.ngram, '%')
AND CHAR_LENGTH(n1.ngram) < CHAR_LENGTH(n2.ngram)
WHERE
n1.... | You are trying to filter the ngrams in the query itself.
It is probably more efficient to do it in two steps.
Start with a table with all possible ngrams:
```
CREATE TABLE original (ngram varchar(100) NOT NULL)
GO
CREATE TABLE refined (ngram varchar(100) NOT NULL PRIMARY KEY)
GO
INSERT INTO original (ngram)
SELECT D... | Find longest matching ngrams in MySQL | [
"",
"mysql",
"sql",
"rdbms",
""
] |
I am having to find and replace a substring over all columns in all tables in a given database.
I tried this code from sqlserver 2012 ssms but resulting in errors from <http://www.dbtalks.com/uploadfile/anjudidi/find-and-replace-string-values-in-all-tables-and-column-in-s/> [Find and Replace string Values in All Table... | Just as a guess, to add delimiters to your table names, modify the script you linked to by editing this line:
```
SET @sqlCommand = 'UPDATE ' + @schema + '.' + @table + ' SET [' + @columnName + '] = REPLACE(convert(nvarchar(max),[' + @columnName + ']),''' + @stringToFind + ''',''' + @stringToReplace + ''')'
```
a... | Are you sure table names may begin with a digit? If so, include them in '[' ']', like
```
UPDATE [dbo].[153TypeTest2].....
``` | how to do a search and replace for a string in mssql 2012 | [
"",
"sql",
"sql-server",
"sql-server-2012",
"ssms-2012",
""
] |
I have the following table
```
Type SubType value
A 1 1
A 2 2
A 3 3
A 4 4
B 1 1
B 2 2
B 3 3
C 1 1
C 2 2
C 3 3
C 4 4
```
I want to group by all rows except where Type=A and the output should like... | Yes, you have to write an expression that creates the group definition:
```
Select case When Type = 'A' then type + ltrim(str(subtype, 9))
Else Type End Type, Sum(Value) Sum
From table
Group By case When Type = 'A' then type + ltrim(str(subtype, 9))
Else Type End
``` | Yes, you can `GROUP BY` a `CASE` expression;
```
SELECT CASE WHEN type='A'
THEN type+CAST(subtype AS VARCHAR(MAX))
ELSE type END [Type],
SUM(value) [Sum]
FROM mytable
GROUP BY CASE WHEN type='A'
THEN type+CAST(subtype AS VARCHAR(MAX))
ELSE type END
ORDER BY [... | How to group by using multiple conditions | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a program that retrieves data and stores it in a table each day, and then another program that queries that data to produce reports. The reports need to say when the data was last updated, so we know how old the information is.
It seems wasteful to add a column with the last update date to the table, since all ... | My preferred way is to create a new "report" table to store the last time the target table is updated, and create a trigger to update the "report" table whenever there is change on the target table.
See this for more information on creating such trigger:
<http://www.techonthenet.com/oracle/triggers/after_update.php> | You Probably should add a column "LastModified" and save the datetime when its getting updated. This should be the best way to identify when your table was last updated. | Best way to keep track of when a table was last updated? | [
"",
"sql",
"oracle",
"database-design",
"oracle11g",
""
] |
I have 2 tables 1st table contains following columns,
```
id code Name
1 c1 chk1
2 c2 chk2
3 c3 chk3
```
2nd table contains following columns,
```
id,Name,Chk1,chk2,Chk3
```
i have to add the column 'Chk4' into table2 if table1 is updated with value '4,'c4','ch4' dynamically.How to write procedure to p... | use this query as procedure.
```
CREATE PROC ADD_CHECK
AS
BEGIN
DECLARE @COLUMN VARCHAR(50)
DECLARE @QUERY VARCHAR(255)
DECLARE @QUERY1 VARCHAR(255)
SET @COLUMN= (SELECT TOP 1 NAME FROM TABLE1 WHERE ID=(SELECT MAX (ID) FROM TABLE1))
IF EXISTS(SELECT 1 FROM TABLE1 WHERE NAME=@COLUMN)
BEG... | Try this:
```
CREATE PROCEDURE <procedurename>
AS
BEGIN
DECLARE @COLUMN varchar(10), @SQL Varchar(100);
SELECT @COLUMN = Name FROM Table1
WHERE id = (SELECT MAX(id) FROM Table1)
IF NOT EXISTS(
SELECT COLUMN_NAME
FROM INFORMA... | How to add dynamic column to an existing table | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2008-r2",
"sql-server-2012",
""
] |
We are receiving rather large files, of which we have no control over the format of, that are being bulk-loaded into a SQL Server table via SSIS to be later imported into our internal structure. These files can contain over 800 columns, and often the column names are not immediately recognizable.
As a result, we have ... | This script will search all tables and all string columns for a specific string. You might be able to adapt this for your needs:
```
DECLARE @tableName sysname
DECLARE @columnName sysname
DECLARE @value varchar(100)
DECLARE @sql varchar(2000)
DECLARE @sqlPreamble varchar(100)
SET @value = 'EDUQ4' -- *** Set this to t... | One option you have is to be a little creative using XML in SQL Server.
Turn a row at a time into XML using cross apply and query for the nodes that has a certain value in a second cross apply.
Finally you output the distinct list of node names.
```
declare @Value nvarchar(max)
set @Value= 'b'
select distinct T3.X... | Selecting column names that have specified value | [
"",
"sql",
"sql-server",
""
] |
In my database, i created a table name DEPTLOC
```
//DEPTLOC
DNAME CITY
----------------------------
RESEARCH BOSTON
IT PARIS
SCIENCE LONDON
RESEARCH LONDON
SALES NEWYORK
RESEARCH PARIS
RESEARCH NEWYORK
MARKETING NEWYORK
```... | Here's a shorter (than my previous answer) query that checks only between DNAMES SALES and RESEARCH to see which DNAME has all CITIES. Set operators UNION ALL and MINUS are used.
```
SELECT DNAME
FROM
(
SELECT 'SALES' DNAME, COUNT(*) MISSING_CITIES
FROM
(
SELECT DISTINCT CITY FROM DEPTLOC
MINUS
SE... | One way of doing this is to count the distinct locations, and join it on the departments query:
```
SELECT dname
FROM (SELECT dname, COUNT(*) AS dept_city_count
FROM deptloc
GROUP BY dname) d
JOIN (SELECT COUNT (DISTINCT city) AS city_count
FROM deptloc) ON city_count = dept_cirt_co... | SELECT clause with MINUS INTERSECT and UNION | [
"",
"sql",
"oracle",
""
] |
I want to drop and add a constraint
```
ALTER TABLE [dbo].[Entity] DROP CONSTRAINT [x_UpdateDate1]
-- default value
ALTER TABLE [dbo].[Entity] ADD CONSTRAINT [x_UpdateDate1]
DEFAULT ([dbo].[GETSYSTEMDATE]())
FOR [CreateDate]
```
I want to find the alternati... | No. You cannot alter a constraint, you need to drop it and then recreate it just as you did. | No, there's no other way than to drop and re-create constraints ([check also sqlauthority.com blog entry](http://blog.sqlauthority.com/2011/04/24/sql-server-how-to-alter-constraint/)) | Dropping and adding a constraint in sql | [
"",
"sql",
"sql-server",
""
] |
I have a table as follows
```
fab_id x y z m
12 14 10 3 5
12 10 10 3 4
```
Here im using group by clause on id .Now i want to subtract those column values which have similar id.
e.g group by on id (12). Now to subtract (14-10)X, (10-10)Y, (3-3)z, (5-4)m
I know there is a aggregate function sum for ... | Now, that you have given more information on how to deal with more records and that you revealed that there is a time column involved, here is a possible solution. The query selects the first and last record per fab\_id and subtracts the values:
```
select
fab_info.fab_id,
earliest_fab.x - latest_fab.x,
earlies... | Seeing as you say there will always be two rows, you can simply do a 'self join' and subtract the values from each other:
```
SELECT t1.fab_id, t1.x - t2.x as diffx, t1.y - t2.y as diffy, <remainder columns here>
from <table> t1
inner join <table> t2 on t1.fab_id = t2.fab_id and t1.correctiondate > t2.correctiondate
`... | SQL - subtract value from same column | [
"",
"sql",
"sql-server-2008",
""
] |
I have a few related questions about MySQL indexes:
1. Does MySQL update the index every time something is inserted?
2. When MySQL updates the index due to an insert, does it rebuild the entire index?
3. Is there a way to make MySQL update the index after every x inserts?
I have a lot of inserts in my application and... | MySQL is probably already doing what you describe, as much as it can.
In the case of InnoDB (which should be your default storage engine with MySQL), inserts and updates and deletes change primary key or unique key indexes immediately. But they never rebuild the *whole* index, they add new values into (or take values ... | MySQL doesn't "rebuild" the index after every insert. MySQL inserts one or more rows into an existing index.
MySQL has lots of unusual options, and I don't know all of them. I would be surprised if there were an option that said: "Oh, let the index on the table be out of synch with the data in the table." Doesn't soun... | Does MySQL update the index on all inserts? Can I make it update after every x inserts? | [
"",
"mysql",
"sql",
"indexing",
""
] |
I am trying to delete all records from a table called user\_enrole.I am using this query
```
DELETE * FROM user_enrole
```
I think syntax of my query is not wrong but it is giving me error saying
> #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the ri... | You don't need to use the asterisk in a delete. Just do `DELETE FROM user_enrole` to delete all records.
If you want to delete specific records filtered by one or more conditions, you will specify those conditions in the `WHERE` clause, like so:
```
DELETE FROM user_enrole
WHERE somecolumn > 1
AND anothercolumn = 'Us... | When you write `SELECT * FROM...` the `*` means *everything*, i.e. all fields. All parts of the row(s). It makes no sense to use the same syntax when deleting, because you can only delete entire rows. This is why the syntax is `DELETE FROM...` | Delete query not working in mysql | [
"",
"mysql",
"sql",
""
] |
Is it possible to split a value(X) over several months if it exceeds value(Y), without using a cursor?
For example, I have value X = 505 and I want to split it over as many months as possible with each month having a maximum value of 100 (value Y = 100)?
So my expected output would be:
```
JAN 100
FEB 100
MAR ... | You can use a table of numbers to spread a value over a sequence of months using CROSS APPLY as follows.
```
create table T(
id int,
dat datetime,
val int,
primary key(id, dat)
);
insert into T values (1, '20140101', 100);
insert into T values (2, '20140101', 99);
insert into T values (3, '20140201', 274);
in... | A little math can help, bit math.
Using the table from the answer of Steve Kass
```
declare @chunk int = 100;
WITH Base(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1
... | SQL Server - splitting a value over several months without a cursor | [
"",
"sql",
"sql-server",
""
] |
I have the weirdest problem and my extremely basic knowledge of SQL must be terribly wrong, but I cannot make sense of the behaviour illustrated below.
I have this file `test.csv`
```
id,field
A,0
B,1
C,2
D,"0"
E,"1"
F,"2"
G,
H,""
I," "
```
And this test code:
```
#! /usr/bin/perl
use strict;
use warnings;
use DBI... | I confirm it's a bug of SQL::Parser:
```
'where_clause' => HASH(0x7f9686737480)
'arg1' => HASH(0x7f9686808248)
'arg1' => HASH(0x7f96866b50f8)
'fullorg' => 'field'
'type' => 'column'
'value' => 'field'
'arg2' => HASH(0x7f968588dfe0)
'fullorg' => 0
'type' => 'number'
... | SQL logic for DBD::CSV is NOT contained in DBD::CSV, which is just a thin glue layer between Text::CSV\_XS and DBI.
All SQL knowledge is dealt with by SQL::Statement. If you think you found a real bug, please try to dig in that module and find the cause, create a patch and post the issue with the patch on RT :) | Perl, DBI, and SQL: Why NOT does not work in some SQL queries? | [
"",
"sql",
"perl",
"csv",
"dbi",
""
] |
I have two simple SQL tables defined below:
* friend(id1, id2)
* Person(id, name)
The friend table is like:
```
Id1 Id2
1 2
1 3
2 3
3 4
```
How can i query the database for the pair of names of friends, omitting the duplicate?
(That mea... | Use a projection to ensure that the friend pairs are ordered lowest first, which makes the duplicate elimination trivial using `DISTINCT`:
```
WITH OrderedFriends AS
(
SELECT
CASE WHEN ID1 < ID2 THEN ID1 ELSE ID2 END AS ID1,
CASE WHEN ID1 < ID2 THEN ID2 ELSE ID1 END AS ID2
FROM Friends
)
SE... | ```
SELECT p1.name,
p2.name
FROM Friend AS f1
JOIN Person AS p1 ON p1.id = f1.id1
JOIN Person AS p2 ON f1.id2 = p2.id
WHERE f1.id1 < f1.id2
```
May be this. | removing duplicate results from friendship table query | [
"",
"sql",
""
] |
I designed following skill database with three tables:
1. employees with columns name, personnelnumber
2. skills with columns skillname, skillid
3. skillmapping with columns skillid, personnelnumber, skilllevel
1) and 2) just assign numbers to persons and skills. 3) assigns skill levels to employees.
For example, ro... | I'd use a subquery to count the number of skill matches a person has, and make sure it comes up as three:
```
SELECT name
FROM person
WHERE personnelnumber IN (SELECT personnelnumber
FROM skillmapping
WHERE (skillid = 2 AND skilllevel = 3) OR
... | Should be a fairly straight forward inner join;
```
SELECT e.*
FROM employees e
JOIN skillmapping s1 ON s1.personnelnumber = e.personnelnumber
AND s1.skillid = 2
AND s1.skillevel = 3
JOIN skillmapping s2 ON s2.personnelnumber = e.personnelnumber
AND s2.sk... | Query for a skill database | [
"",
"sql",
""
] |
**Hi please help me. How join 3 columns with null values?.**
```
SELECT [item],[Prox],[z], [item]+[Prox]+[z] as result FROM [FIELD$];
```
**Result.**
 | As concatenating multiple strings with at least one null value results in `NULL` you may use `coalesce` to solve this:
```
SELECT
[item],
[Prox],
[z],
coalesce([item], '') + coalesce([Prox], '') + coalesce([z], '') as result
FROM
[FIELD$];
```
`coalesce` is ANSI standard and available in almost al... | Try this:
```
SELECT [item],[Prox],[z], COALESCE([item],'')+COALESCE([Prox],'')+COALESCE([z],'') as result
FROM [FIELD$];
```
**Explanation:**
`COALESCE` evaluates the arguments in order and returns the current value of the first expression that initially does not evaluate to NULL.
i.e., If `[item]` is `NULL`, the... | How join columns with null value? | [
"",
"sql",
"sql-server",
"database",
"join",
""
] |
I want to create a barcode by merge and combine two column.
here is my table :
```
ID | Items1 | Items2 | BArcode
001 | Shirt | CPU |
002 | Shirt | CPU |
001 | Shoes | Monitor |
002 | Jacket | Monitor |
001 | Shoes | CPU |
002 | ... | You can use this query to generate the `barcode` values:
```
;with cte as
(select id, item1 item, row_number() over (partition by id, item1 order by getdate()) rn
from items
where item1 is not null and barcode is null
union
select id, item2 item, row_number() over (partition by id, item2 order by getdate()) rn
f... | The error that you are getting is that the union join that you have created does not contain the same fields in the second select statement, as your original select statement. [SQL UNION Operator](http://www.w3schools.com/sql/sql_union.asp), Notice that each SELECT statement within the UNION **must have the same number... | SQL SERVER merge two column, combine it, and count the same | [
"",
"asp.net",
"sql",
"sql-server",
"vb.net",
""
] |
I'm trying to generate a random time between 8:00 AM and 8:00 PM *for each row* that is selected from a data set, however, I always get the ***same*** random value for each row – I want it to be ***different*** for each row.
*Table schema & data:*
```
╔══════╦════════════════╗
║ ID ║ CREATED_DATE ║
╠══════╬══════... | ## Interpretation of Original Question:
The question states:
* Generate a *random* time between 8:00 AM and 8:00 PM (i.e. a 12-hour window)
* It should be different *for each row* (i.e. unique across all rows)
* The real table has around 2800 records
Now factor in the following points:
* Sample data shows only a si... | The issue *OP* had while using just `rand()` is due to it's evaluation *once per query*.
*From the [**documentation**](https://msdn.microsoft.com/en-us/library/ms177610.aspx):*
> If *seed* is not specified, the SQL Server Database Engine assigns a *seed* value at random. For a specified *seed* value, the result retur... | Distinct random time generation in the fixed interval | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
"random-time-generation",
""
] |
I want to count all goals in a soccer match in the first and second halftime, but I only have the data for the first halftime and the final score.
```
SELECT SUM( scorehome_ht + scoreguest_ht ) AS halftime,
(SUM( scorehome_end + scoreguest_end ) - halftime) AS end
FROM matches;
```
I'm new at stackoverflow, not... | An alias assigned to a column can't be referenced by another expression in the SELECT list.
One workaround is to repeat the expression, and that's usually the most efficient, in terms of performance, e.g.
```
SELECT SUM( scorehome_ht + scoreguest_ht ) AS halftime,
SUM( scorehome_end + scoreguest_end ) - SUM( sco... | You can't use aliases in the same select query, but what you can do is wrap them in a derived table:
```
SELECT halftime, scorehome_end + scoreguest_end - halftime AS end
FROM
(
SELECT scorehome_end,
scoreguest_end,
SUM( scorehome_ht + scoreguest_ht ) AS halftime
FROM matches
) x;
``` | SQL alias doesn't work | [
"",
"mysql",
"sql",
""
] |
We have two tables:
```
HUSBANDS
---------------
id
name
surname
age
WIFES
---------------
id
name
surname
age
husbandId --(with constrain -> HUSBANDS.ID)
```
and suppose, that we need to write procedure removing wifes older than 60 years together with their husbands ;)
It could be perfect to d... | You can update the husbands first with an indicator that they have no wife. For your data, let's use `age = -1`. Then delete from wifes [sic] and then delete from husbands.
```
update husbands
set age = -1
where id in (select husbandId from wifes where age >= 60);
delete from wifes where age >= 60;
delete fr... | If no "unmarried husbands" are allowed in the table, you could just first remove the wives, and then all husbands that no longer have a wife. If temporary inconsistency is a problem, you may want to wrap the deletes inside a transaction.
```
PROCEDURE remove_old_wifes() IS
BEGIN
DELETE FROM wifes WHERE age >= 60; ... | Deleting rows from two tables related by constraint | [
"",
"sql",
"oracle",
"plsql",
""
] |
Following is the table:
```
emp_id salary salary_date
Emp1 1000 Feb 01
Emp1 2000 Feb 15
Emp1 3000 Feb 28
Emp1 4000 Mar 01
Emp2 5000 Jan 01
Emp2 6000 Jan 15
Emp2 2000 Mar 01
Emp2 5000 Apr 01
Emp3 1000 Jan 01
Emp4 3000 Dec 31
Emp4 5000 Dec 01
```
An... | I have found my answer!!!
select emp\_id, substr(sal\_date,1,3) monthly, salary from
(select emp\_id, sal\_date, salary,
max(salary)over (partition by substr(sal\_date,1,3)) max\_sal from emp\_salary order by emp\_id)
where salary=max\_sal;
Result-set:
EMP\_ID MONTHLY SALARY
---
Emp1 Mar 4000
Emp1 Feb 3000
Emp2 Ja... | ```
SELECT e.Emp_ID,MaxSalary,MonthName
FROM employeeTable e
INNER JOIN
(
SELECT MAX(salary) as MaxSalary,
LEFT(salary_date,3) as MonthName
FROM employeeTable
GROUP BY LEFT(salary_date,3)
)t
ON e.Salary=t.MaxSalary
``` | I have an emp_salary table with emp_id, salary and salary_date. I want to write a query to find out which employee was paid highest in every month | [
"",
"sql",
"date",
"select",
"oracle11g",
"highest",
""
] |
This question was asked for [MySQL](https://stackoverflow.com/questions/4418776/what-is-the-default-mysql-join-standalone-inner-or) already, but for Transact-SQL, what is the default `JOIN` behaviour?
That is, is simply writing `JOIN` in a query synonymous with writing `INNER JOIN` (as is the case with MySQL), or some... | `JOIN` defaults to `INNER JOIN` behaviour.
To verify this, I ran the following code:
```
DECLARE @A TABLE (x INT)
INSERT INTO @A
SELECT 1 UNION ALL
SELECT 2
DECLARE @B TABLE (x INT)
INSERT INTO @B
SELECT 2 UNION ALL
SELECT 3
SELECT
A.x AS 'A.x',
B.x AS 'B.x'
FROM @A A
JOIN @B B
ON A.x ... | In T-SQL, `JOIN` without an explicit type is an `INNER JOIN`, as specified by [the documentation on the `FROM` clause](https://msdn.microsoft.com/library/ms177634) (excerpt):
```
[ FROM { <table_source> } [ ,...n ] ]
<table_source> ::=
{
...
| <joined_table>
...
}
<joined_table> ::=
{
... | What is the default T-SQL JOIN behaviour, INNER or OUTER? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have one table (in MySQL) like this:
```
subject | predicate | object
A | P1 | X
X | P2 | B
```
I want to know transitive relation by using this table, so the result should like this:
```
element1 | predicate1 | pivot | predicate2 | element2
A | P1 | X | P2 | B
... | Use a [self join](https://stackoverflow.com/questions/1284441/how-does-a-mysql-self-join-work):
```
SELECT
a.subject as element1,
a.predicate as predicate2,
a.object as pivot,
b.predicate as predicate2,
b.subject as element2 FROM
table a JOIN
table b ON a.object = b.subject;
``` | I would write a simple `JOIN`:
```
select p1.subject, p1.predicate, p1.object, p2.predicate, p2.object
from some_relation p1
inner join some_relation p2 on p1.object = p2.subject and p2.object = 'B'
where p1.subject = 'A'
```
Or do you mean something different? | Select Transitive Relation on One Table | [
"",
"mysql",
"sql",
""
] |
I have a MS SQL Server express 2012 table that is constantly being populated with data to let us know which of our products are available. Under each product are one or many sub\_products. When the process that updates the product does its update, it also updates all sub\_products at the same time. (thus all will have ... | Probably the most efficient way to do this is with a `not exists` clause:
```
select *
from project_data pd
where not exists (select 1
from project_data pd2
where pd2.product = pd.product and
pd2.founddate > pd.founddate
);
```
The logic is:... | Here's another option joining the table to itself using `Max`:
```
select pd.product, pd.sub_product, pd.founddate
from project_data pd
join (select product, max(founddate) maxdt
from project_data
group by product
) t on pd.product = t.product and pd.founddate = t.maxdt
```
* [Updated Fiddle... | Need help creating SQL query to most recent data | [
"",
"sql",
"sql-server",
""
] |
If I create a table with an entity that is suppose to be `DATE` and when I `Insert` and leave that column blank shouldn't it display the current date? Same with time?
For example...
```
CREATE TABLE Register
(
Name CHAR(20) NOT NULL,
Date DATE,
Time TIME
);
```
Then I Insert:
```
INSERT INTO Register (Name)
VALUES ... | ***Firstly***, you should have a `PRIMARY KEY` in your table.
***Secondly***, you have not set default values for columns `Date` and `Time`. Also, you can't set them separately for the `DATE` and `TIME` types – you should use `TIMESTAMP` type and `DEFAULT CURRENT_TIMESTAMP` like :
```
CREATE TABLE Register (
Nam... | Here are two options:
1. Get rid of `Date` and `Time` columns and add `time stamp`
`INSERT INTO Register (Name,Ctime) VALUES ('Howard',CURRENT_TIMESTAMP);`
2. If you want to continue with your table structure
`INSERT INTO Register (Name,`Date`,`Time`) VALUES ('Howard',CURDATE(), CURTIME());`
Also Note that `d... | INSERT current date or time into MySQL | [
"",
"mysql",
"sql",
""
] |
I have a table
```
id | name | ts
------+------------+---------------------
3812 | name1 | 2014-05-01 00:10:02
3900 | name1 | 2014-05-02 00:10:03
3838 | name2 | 2014-05-01 00:10:08
3893 | name3 | 2014-05-02 00:10:02
3933 | name2 | 2014-05-02 00:10:14
3977 | name3 | ... | Assuming ID is incremented sequentially...
naming a table and column in the table with the same name may cause trouble later...
```
Select max(n.ID), n.name, max(n.TS)
From Name n
group by n.name
```
However if ID is not sequential -- and assuming name and ts are UNIQUE...
```
Select a.id, a.name, a.ts
from name a... | ```
select id, name, ts
from (
select id,
name,
ts,
max(ts) over (partition by name) as max_ts
from the_table
) t
where ts = max_ts;
``` | PgSQL select latest ts for every distinct value in column | [
"",
"sql",
"postgresql",
"select",
"group-by",
"distinct",
""
] |
I am getting an issue and I feel like I fixed everything. MySQL workbench is still giving me this error. If you can please explain what is wrong I would be greatly appreciate it. I did check for key constraints in the Account table. It is giving the error in the account table.
```
CREATE TABLE Account(
AcctNum int... | You need to create the referencing table first before creating the table which is referring other tables with FOREIGN key.
The order of table creation should be as
```
CREATE TABLE Member(
MemNum int AUTO_INCREMENT,
DOB date,
CreditScore int,
AcctOpened date,
SSN VARCHAR(11),
Address V... | Ofcourse the order of table creation is important here.
Create the Member and Employee tables first, followed by the Account. It should work fine. | Error Code: 1215 in mysql cannot add foreign key constraint | [
"",
"mysql",
"sql",
""
] |
Hello everyone I have spent a few days looking at ways to connect to SQL server using vba and found an interesting post by microsoft on how to setup a DSN-less connection they have provided the code this is what it looks like.
```
'//Name :AttachDSNLessTable
'//Purpose:Create a linked table to SQL Server without using... | If this code works for you but you need a better place to execute it/a place that will execute that is not tied to that form's definition you can run it in the AutoExec macro.
The `AutoExec` macro is a macro named `AutoExec` which runs when you start your Access app. You can use the `RunCode` macro function to call yo... | Open a blank form, with a fixed data record as source. Run your Code, then change the source form to your real form (VBA Code in OPEN FORM action) according to what you want to do. This is SMOKE and MIRROW Code. You will have one hell of a time debugging it. | Connecting to sql server using access vba | [
"",
"sql",
"sql-server",
"ms-access",
"vba",
""
] |
Consider the following query which generates customerid and days on which they bought a particular product, clearly each customer will have different dates on which he/she bought an item. What I want to do is get total purchase made on those days that the customer bought that product.
I have the ff query.
```
Select ... | After thinking through carefully the following worked for me, and is faster.
--drop table #days
select customerid, eventdate
into #days
from table1
with(nolock, index(ix\_eventdate))
WHERE EVENTDATE between 20140401 and 20140430
and product='chocolate'
--drop table #pur
select customerid, eventdate, purchases
into ... | This gives sum of purchases for each customer **AND** for each of that day on which chocolate was purchased.
```
select customerid, eventdate ,sum(purchases) purchases
into #pur
from table1
where product='chocolate'
group by customerid,eventdate
```
If you want total purchase when chocolate was brought then do this
... | How to sum over selected dates from table | [
"",
"sql",
"sql-server",
""
] |
There are three tables
Students, Courses and Registration
```
Students has id, name columns
Courses has also course.id, course.name
```
and there is third table joining the Students and Courses table
```
Registration : stu_id, course_id
```
One Student can take one or many courses.
I would like to find the n... | Try with INNER JOIN
```
SELECT S.id, S.name
FROM students S
INNER JOIN registration R ON S.id = R.stu_id
GROUP BY S.id, S.name
HAVING COUNT(*) = 1
``` | Like below:
```
SELECT s.id, s.name
FROM students s
LEFT JOIN registration r ON s.id = r.stu_id
GROUP BY s.id, s.name
HAVING COUNT(r.course_id) = 1
``` | SQL query to find the students in one course | [
"",
"mysql",
"sql",
""
] |
I am using following query to do this
```
select (Col_A + Col_B) Foo,
(Col_C + Col_D) Bar,
(Col_A + Col_B + Col_C + Col_D) FooBar from Table1
```
But is there a way like to do like this
```
select (Col_A + Col_B) Foo,
(Col_C + Col_D) Bar,
(Foo + Bar) FooBar from Table1
```
it gives Error... | Partial solution is to use `with` construction:
```
with query as (
select (Col_A + Col_B) Foo,
(Col_C + Col_D) Bar
from Table1)
select Foo,
Bar,
Foo + Bar
from query
``` | Afaik those columns you're referring to don't exist by those names yet.
You can of course try the following instead:
```
SELECT *, (Foo + Bar) FooBar
FROM (select (Col_A + Col_B) Foo,
(Col_C + Col_D) Bar
from Table1) SRC
``` | How to add dynamic Columns in SQL? | [
"",
"sql",
"sql-server",
""
] |
I have a stored procedure that fetches records based on dates matching a date input which works fine so far.
Both the dates in the table and my input date are formatted as datetime.
Instead of comparing the full dates I would like to change this so that it only compares month and day so that it works with any year for... | You can do something like this ;)
```
ALTER PROCEDURE [dbo].[FetchDays]
@inputDate datetime
AS
BEGIN
SET NOCOUNT ON;
SELECT dateID,
dayDT,
countries,
regions
FROM DaysDT
WHERE
DAY(dayDT) = DAY(@inputDate) --Extract and compa... | Try this:
```
WHERE datepart(day, dayDT) = datepart(day,@inputDate)
AND datepart(month, dayDT) = datepart(month,@inputDate)
```
This will compare the date and month parts of your overall date, without checking the year. | SQL Server: compare dates by only matching month and day | [
"",
"sql",
"sql-server",
"date",
"stored-procedures",
""
] |
I am writing an SSIS Expression that creates a Date Key to be used with a DimDate table.
I need the Expression to return the previous Month not the Current month.
```
(DT_STR, 4,1252)YEAR(GETDATE()) + RIGHT("0" + (DT_STR, 2, 1252) MONTH(GETDATE()),2) + RIGHT("0" + (DT_STR, 2, 1252) DAY( GETDATE()), 2)
```
I tried pu... | Try this when you are retrieving the Month part -
RIGHT("0" + (DT\_STR, 2, 1252) MONTH( DATEADD("MONTH",-1,GETDATE()) ),2) | ```
DATEADD("Month", -1,GETDATE())
```
use code above that can make sure it comes with Year and Date also. then you can present the datetime with any format | Return Previous Month in SSIS Expression | [
"",
"sql",
"sql-server",
"ssis",
""
] |
What is the purely MySQL way of getting yesterday, but only for business days?
Right now I'm using `SUBDATE(CURRENT_DATE, 1))` for yesterday but on Monday it's returning Sunday.
I would like it to return results for the previous Friday's date, or in other words, the previous business day.
I should have clarified I'm... | ```
SELECT ..
.
.
AND DATE(a.scantime) = (CASE WEEKDAY(CURRENT_DATE)
WHEN 0 THEN SUBDATE(CURRENT_DATE,3)
WHEN 6 THEN SUBDATE(CURRENT_DATE,2)
WHEN 5 THEN SUBDATE(CURRENT_DATE,1)
ELSE SUBDATE(CURRENT_DATE... | try this to get the day:
```
SELECT
CASE DAYOFWEEK(SUBDATE(CURRENT_DATE, 1))
WHEN 1 THEN SELECT SUBDATE(CURRENT_DATE, 3);
WHEN 7 THEN SELECT SUBDATE(CURRENT_DATE, 2);
ELSE
BEGIN
SUBDATE(CURRENT_DATE, 1);
END;
END CASE;
```
THEN use a subquery
```
SELECT ... WHERE ... | Select the previous business day by using SQL | [
"",
"mysql",
"sql",
"date",
""
] |
I have two tables. Cat and Data.
```
Cat
Cat_Serno
Cat_Name
Data
Data_Serno
Data_Name
Data_Cat_ID
Data_Project_ID
```
When i Am doing a regular join I am getting
```
SELECT t1.*,t2.*
FROM Cat t1
LEFT JOIN Data t2 ON t1.Cat_Serno = t2.Data_Cat_Id
```

```
Please note, that NULL is not equals to any values (including NULL), so you have to handle it.
Another way:
```
WHERE COALESCE(DataName, 'n/a') IN ('D... | Joining Two Tables with Where Clause | [
"",
"sql",
"sql-server",
"sql-server-2008",
"join",
""
] |
I have this sql query
```
SELECT `price` FROM `used_cars` ORDER BY `price` DESC
```
So I obviously want to order by price from high to low. However, it seems to be taking the first digit and sorting by that. My theory is that it is treating it like a string, and as the column is a varchar it makes sense. However, thi... | CAST should work:
```
SELECT CAST(price AS UNSIGNED) AS NumPrice
FROM used_cars
ORDER BY NumPrice DESC
``` | You should convert the column to a numeric data type. You can do that in the table definition, or in the query itself, for example with:
```
... ORDER BY `price`+0 DESC
``` | ORDER BY DESC is not working right | [
"",
"mysql",
"sql",
""
] |
In the below code, I need to check if the table exists in each line. Please tell me how to do it.
```
Select * from Table 1 union all
select * from Table 2 union all
Select * from Table 3
```
I tried this but didn't work
```
if objectid ('Table1') is not null
Select * from Table 1 union all
if objectid ('Table2') is... | A possible solution would be this:
```
USE MyDB;
DECLARE @recordsExistingTables TABLE(Column1 nvarchar(50), Column2 nvarchar(50));
IF (EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'Table1'))
BEGIN
INSERT INTO @re... | Tried to create a sort of generic solution. Created a procedure, where you have to pass all table names in comma separated values and it will return the complete data list of all tables.
```
Create Procedure spGetTableData
@tableNames varchar(4000) --expecting all table names in csv format here
As
Begin
declare @sql n... | Union all if the table exists in SQL server 2008 | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I need some help with refreshing my memory on how to query correctly.
```
CREATE TABLE Editor
(eid CHAR(4) PRIMARY KEY NOT NULL,
fname VARCHAR(15),
lname VARCHAR(15));
CREATE TABLE Edited_by
(eid CHAR(4) NOT NULL,
isbn CHAR(10) NOT NULL);
```
Now I need to query an ISBN #3489374345 and get the eid, fn... | ```
SELECT e.eid, e.fname, e.lname
FROM Editor e inner join Edited_by b
on e.eid=b.eid
WHERE b.isbn='3489374345'
``` | Here, you are trying to retrieve data from Editor table (at least fname and lname) and your 'where' condition is applied on 'Edited\_by' table. So, you need to join the table. And before joining the table, as 'eid' of 'Edited\_by' table would definitely be a subset of 'eid' of 'Editor' table, you should add a foreign k... | Queries MySQL tables | [
"",
"mysql",
"sql",
""
] |
I am pretty new to SQL and hope someone here can help me with this.
I have a stored procedure where I would like to pass a different value depending on whether a column contains a certain country or not.
So far I only used `CASE` when checking for the match with a specific number or value so I am not sure about this ... | This is the syntax you need:
```
CASE WHEN countries LIKE '%'+@selCountry+'%' THEN 'national' ELSE 'regional' END
```
Although, as per your original problem, I'd solve it differently, splitting the content of @selcountry int a table form and joining to it. | Add an `END` before alias name.
```
CASE WHEN countries LIKE '%'+@selCountry+'%' THEN 'national'
ELSE 'regional'
END
AS validity
``` | SQL Server: use CASE with LIKE | [
"",
"sql",
"sql-server",
"stored-procedures",
"case",
"sql-like",
""
] |
does anybody have any suggestions to optimize this query :
```
SELECT COUNT(client_id) FROM (
SELECT client_id FROM `cdr` WHERE
(DATE(start) BETWEEN '2014-04-21' AND '2014-04-25') AND
`service` = 'test'
GROUP BY client_id
HAVING SUM(duration) > 300
)as t1
```
The problem is , inner query scans... | Try below query, avoid functions in searching as it does not use index and kill the performance. "start" columns must be indexed.
```
SELECT COUNT(client_id) FROM (
SELECT client_id FROM `cdr` WHERE
(start BETWEEN '2014-04-21 00:00:00' AND '2014-04-25 23:59:59') AND
`service` = 'test'
GROUP BY client_... | Why not this?I have read somewhere that comparing dates directly with < or > works faster than Between.
```
SELECT Count(client_id) FROM `cdr`
WHERE DATE(start) >= '2014-04-21'
AND DATE(start) <= '2014-04-25'
AND `service` = 'test'
GROUP BY client_id
HAVING SUM(duration) > 300
```
What was logic behind... | Let me know if i can optimize this query? | [
"",
"mysql",
"sql",
"optimization",
""
] |
I'm trying to append certain rows from a table to another table. I used a SQL command to get the rows I wanted and Microsoft SQL Server Management Studio gave the output in the format of .RPT. So I want to append this RPT to my SQL table.
Is there a way to convert RPT to SQL so I can import it? If not, how do I downlo... | I was able to open the RPT file in Excel, manipulate it, then save as CSV to import into PHPMyAdmin. | Here are the [steps](https://stackoverflow.com/a/56188149/5070440) to import the .rpt file to a SQL Server table. I will link to it instead of repeating it here. To summarize the steps, you can use the Import Export wizard and load it as a Ragged right file of format UTF-8. | Import RPT (Output from Select command) to SQL Table | [
"",
"sql",
""
] |
I want to convert a dateTime value to Month-Year (note the **(-)** between them).
i want them like Jan-2014, Feb-2014, Mar-2014, Apr-2014.
i have tried
```
SELECT convert(varchar(7), getdate(), 126)
SELECT right(convert(varchar, getdate(), 106), 8)
```
But the first line gives me 2014-05 (i need it like May-2014) ... | You were almost there:
```
SELECT replace(right(convert(varchar, getdate(), 106), 8), ' ', '-')
``` | Write as:
```
SELECT REPLACE(RIGHT(CONVERT(VARCHAR(11),
GETDATE(), 106), 8),
' ', '-') AS [Mon-YYYY]
``` | Converting datetime to month-year only - T-SQL | [
"",
"sql",
"sql-server",
"t-sql",
"datetime",
""
] |
i am trying to fill a variable in PL/SQL with an if-condition value
like this:
`v_variable := if(4 > 3) THEN 'A' ELSE 'B' END;`
but this doesnt work.
Are there any options to do this? | Instead of doing this with an `if`, I'd go with `case`:
```
v_variable := case when 4>3 then 'A' else 'B' end;
``` | Try this:
```
IF (4 > 3) THEN
v_variable :='A';
ELSE
v_variable :='B';
END IF;
``` | PL/SQL fill variable with if-condition value | [
"",
"sql",
"variables",
"plsql",
""
] |
I have two tables, **likes** and **comments** both of which refer to topic posts - like a topic of a forum for example.
Both of them have a column that refers to a specific topic\_id.
Now here's the deal: i want to create a top 5 chart of most liked + commented, the total of both summed up i mean, topics.
For exampl... | ```
SELECT posts.id, count(comments.id) + count(likes.id) AS score
FROM posts
LEFT JOIN comments ON posts.id = comments.post_id
LEFT JOIN likes ON posts.id = likes.post_id
GROUP BY posts.id
ORDER BY score desc;
```
For those interested here's the solution. | This will works like a charm!!
```
SELECT topics.id
,count(DISTINCT(comments.id)) + count(DISTINCT(likes.id)) AS score
FROM topics
LEFT JOIN comments ON topics.id = comments.post_id
LEFT JOIN likes ON topics.id = likes.post_id
WHERE topics.to_user = 'someuser'
GROUP ... | Counting likes and comments between two different table of a specific topic | [
"",
"mysql",
"sql",
"count",
"sum",
""
] |
I get the error code `ORA-12704` with the following query:
```
SELECT COALESCE(BankDetails.description,'') as description FROM BankDetails
```
The datatype of description column nvarchar2. I'm assuming the `''` is the cause of the issue as this is not matching with the datatype. | Try this
```
SELECT COALESCE(BankDetails.description,n'') as description FROM BankDetails
```
Reference
[ORA-12704: character set mismatch](https://stackoverflow.com/questions/15967201/ora-12704-character-set-mismatch) | You should use the `n` variant, to cast the `''` to a `nvarchar`:
```
SELECT COALESCE(BankDetails.description,n'') as description FROM BankDetails
``` | ORA-12704: character set mismatch with nvarchar2 datatype in Oracle | [
"",
"sql",
"oracle",
""
] |
Here in below table i want to update the second row opening with first row closing and so on.
Closing column is calculated as (opening + Total)
```
ID opening Total Closing
--- -------- ------------ -------------
1 0 3015591.25 3015591.25
2 0 2146798.4 NULL
3 0 3015591.25 N... | An answer involving `WHILE` loop.
```
--Simulated your table
DECLARE @tbl TABLE
(
ID INT,
opening FLOAT,
Total FLOAT,
Closing FLOAT
)
--Testing values
INSERT INTO @tbl(ID, opening , Total ,Closing) VALUES(1,0,3015591.25,3015591.25)
INSERT INTO @tbl(ID, opening , Total ,Closing) VALUES(2,0,2146798.4,... | You can use this query which is based on the fact that your closing value is the sum of totals from all previous rows (current row included) and opening value is the same not including the current row.
```
update table1
set
Opening = isnull((select sum(total) from table1 t where t.ID < table1.ID), 0),
Closing ... | How to update running records in SQL Server | [
"",
"sql",
"sql-server",
""
] |
I have 2 Tables Company and Car.
```
Company:
CompanyId,
CarId,
Inative: 1 or 0.
Car:
CarId,
Plate.
```
The problem is:
In the same month a Car could be rented for more than one Company and I have to bring only the last company that the car was rented.
```
SELECT CompanyId
from Company
where
-- S... | Your case:
```
SELECT CompanyId
from Company
WHERE
-- Some Business Rules
ORDER BY CompanyId DESC
LIMIT 1
```
But as i undestood You have to normalize Your DB first.
There should be 3 tables:
Company,
Car,
Car\_to\_company(
id Serial PK,
id\_car integer FK,
id\_company integer FK,
date\_from date
etc... | You don't necessarily need a group by in your main query for this.
Assuming that a date value is unique (i.e. there cannot be two rentals of the same car for the same date) you could do this with a clause like this:
```
...
WHERE date = (SELECT MAX(date) FROM ... )
``` | Can't figure out how to make this GroupBy clause | [
"",
"sql",
"sql-server",
""
] |
In sql server I am trying add a column to my query that will sum the fields of colC wherever colA and colB show to have a duplicate entry.
Example: I am trying to figure out how much money each person has paid in total. Each record represents one payment that a person has made. How do I find the total amount that each... | you can join back on the original table to join the groups back to the original transactions.
```
SELECT
M.FName,
M.LName,
M.total_paid,
X.SUM(ColC) AS total_paid
FROM
MyTable M
INNER JOIN
(
SELECT
FName,
LName,
SUM(ColC) AS total_paid
... | An alternate that may not be terribly efficient given the distinct keyword, but try this.
```
CREATE TABLE PAID ( FName VARCHAR(12), LName VARCHAR(12), [$Paid] NUMERIC(10,2))
INSERT INTO PAID (FName, LName, [$Paid]) VALUES ('Bob','Dole',1);
INSERT INTO PAID (FName, LName, [$Paid]) VALUES ('Bob','Dole',2.2... | SQL: How do you sum he fields in one column, when a separate 2 columns fields are equal | [
"",
"sql",
"sql-server",
""
] |
Alright, I have those columns on MySQL :
```
id
id_conv
associated_statut
```
The **associated\_statut** is a number between `1` and `7`.
What I want to do is to count only the `id_conv` if the **LAST** associated\_statut for this `id_conv` is `2` for example.
Example :
```
----------------------------------------... | Maybe, this will work for you:
```
SELECT count(t1.id) FROM mytable t1
INNER JOIN (SELECT id_conv, MAX(id) id FROM foo GROUP BY id_conv) t2
ON t1.id = t2.id
WHERE t1.associated_statut = 2
``` | We can do same thing without sub query. It will take less time when you have more data.
```
SELECT count(t1.id) FROM
mytable t1
LEFT JOIN
mytable t2
ON t1.id_conv = t2.id_conv
AND t1.id < t2.id
WHERE t2.id IS NULL
AND t1.associated_statut = 2;
``` | MySQL - Count only if the last associated_statut = 2 | [
"",
"mysql",
"sql",
"count",
""
] |
I'm learning about RoR/databases and this topic particularly confused me. In the book *Agile Development with Rails 4* , they give an example of finding a list of all orders with for an entry with name Dave:
```
pos = Order.where("name = 'Dave' and pay_type = 'po")
```
The book goes on to say that you would never wan... | **The simplest Explanation i can give for what SQL injection is:**
This may make a SQL query like the following:
```
SELECT * FROM Order WHERE name = 'Dan' AND pay_type = 'po'
```
Now a nice user would supply the name Dan like above.
But an evil user (let's call him Bobby), would supply the name:
`Bobby Tables'; DR... | It has to do with how the code interpreter works.
In the first example, the parameter is simply inserted as text, and then the entire command is processed. Hence, problems.
In the second example, the command is interpreted first, and then the parameter is inserted afterwards. (IE, it interprets "do statement where na... | How this SQL injection works? Explanation needed | [
"",
"sql",
"ruby-on-rails",
"ruby",
"sql-injection",
""
] |
I have some value with data type Numeric(28,10) (e.g. 128000,0000000000). I want to round it up to 2 significances and convert it into string. What is wrong with this?
```
convert(varchar,round(isnull(td2.Qty,0),2))
```
where td2.Qty is that value. It coverts it to string, but doesn't round it. Thanks in advance | It does round, but it keeps displaying the zeros because this is how `numeric`s are always displayed.
If you need to stop displaying zeros, convert the value to a different type after the rounding, e.g. `float` or `numeric(28,2)`:
```
convert(varchar, cast(round(isnull(td2.Qty,0),2) as numeric(28,2)))
``` | ```
SELECT CAST(round(isnull(128000,0000000000),2)AS FLOAT)
SELECT CAST(round(isnull(128000,0000000000),2)AS NUMERIC(28,2))
``` | rounding and converting value | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I'm currently collecting data from individual tables. I'm supposed to get my sum (amount\*weight) For each shipment. However it gives me the overall sum\*weight, which means I get the same result all the way down.
Here is the code I carried out:
```
SELECT SUM(Weight*Amount), Arrival_Date
FROM Specifications, Shipme... | Extend `GROUP BY` of your query:
```
SELECT SUM(Weight * Amount),
Arrival_Date
FROM Specifications,
Shipment,
`Product shipment`
WHERE Specifications.Product_Code = `Product shipment`.Product_Code
AND `Product shipment`.Shipment_ID = `product Shipment`.shipment_ID
GROUP B... | You should group by shipment\_ID, not Arrival\_Date.
I'm not sure but maybe shipment\_ID needs to appear in the SELECT clause for this to work. | Sql individual SUM | [
"",
"sql",
""
] |
I have a dynamic SQL query with different column names and tables at runtime.
I am looking to get the SQL query to ignore reading data based on if a row contains Null value in any cell.
```
SELECT rsv_intension_rsvt
FROM resolve_table_kb
where rsv_intension_rsvt is not null;
```
I am aware of using `IS NOT NULL`.
... | No, there's no `select where * is not null`-type query. You have to test every field individually:
```
SELECT ...
FROM ...
WHERE field1 is not null AND field2 is not null AND .... AND fieldN is not null
```
You could try a `COALESCE()` operation, perhaps, but that's still ugly:
```
WHERE COALESCE(field1, field2, ...... | I believe you will need to use a stored procedure or multiple joins(which might not be the healthiest solution) to solve this as [Marc B](https://stackoverflow.com/users/118068/marc-b) indicated. You can also check the following [question](https://stackoverflow.com/questions/5285448/mysql-select-only-not-null-values) t... | Dynamic SQL Query to ignore null values based on null value in cell | [
"",
"mysql",
"sql",
"sql-server",
"oracle",
""
] |
Could anybody tell me whether it is possible to have a column within a table in MYSQL that automatically performs the SUM function for a given number of columns.
As a comparative example in Microsoft Excel, it's possible to have a cell that performs the SUM function for a given range of cells and automatically updates... | Normally you would do that in your select query on-the-fly and don't store those calculation.
```
select some_column,
col1 * col2 as some_calculation_result
from your_table
```
But if you have a really good reason not to do it that way then you can use a trigger to calculate those data.
You need an update tri... | I think you will have to do this with a trigger. A column by itself just store data, it can't do things programmatically. | How to create a column in MYSQL which automatically SUMs the values from other columns within the same row | [
"",
"mysql",
"sql",
""
] |
I'm developing my first ever application with PostgreSQL.
# The Scenario
**This is what my table "person" looks like:**
```
Column | Type | Modifiers
------------+-----------------------------+-----------------------------------------------------
id | bigint ... | Some DBMS (like Oracle) treats empty string (`''`) as `NULL`. Others (like MySQL, PostgreSQL, etc) treat empty string and `NULL` as different.
PostgreSQL treats `''` as empty string, not `NULL`, so your `insert` statement executed successfully. | `null` and an empty string are not the same values, by passing in an empty string you have satisfied the requirement.
If you query was
```
insert into person (first_name, last_name, password)
values ('Max', 'Mustermann', '123123123');
```
then an error would be thrown because you are not passing in a value for emai... | PostgreSQL: Why is NOT NULL not working here? | [
"",
"sql",
"postgresql",
"psql",
"postgresql-9.3",
""
] |
On my database table `stocks`, I have the columns:
```
stock_id
make
model
buy_rate
tax
other_charges
```
After inserting data into the above table, I have added a new column named `sell_rate` which is at the moment `NULL`.
* **How do I update data in `sell_rate` using `buy_rate` + `tax` + `other_charges`?** | Try something like that:
```
UPDATE stocks
SET sell_rate = buy_rate + tax + other_charges
``` | You can use update statement as other guys suggested for fill column in records which are already exist.
for fill the column in the future automatically you should set the column as 'Computed Column' by Set:
Table Design -> Computed Column Specification -> Formula to : buy\_rate + tax + other\_charges
But you should ... | How to update new column based on the value of existent columns? | [
"",
"sql",
"sql-server",
""
] |
I need to get a report that shows distinct users per week to show user growth per week, but I need it to show cumulative distinct users.
So if I have 5 weeks of data, I want to show:
Distinct users from week 0 through week 1
Distinct users from week 0 through week 2
Distinct users from week 0 through week 3
Distinct u... | You could try something like this:
```
Declare @Week Int = 1
While @Week <= 52
Begin
select count(distinct user_id) as count
from tracking
where datepart(wk,login_dt_tm) >= 0 and datepart(wk,login_dt_tm) <= @Week
Set @Week += 1
End
``` | Why not something like:
```
select count(distinct user_id) as count, datepartk(wk, login_dt_tm) as week
from tracking
group by datepart(wk,login_dt_tm)
order by week
``` | Growth Of Distinct Users Per Week | [
"",
"sql",
"sql-server",
""
] |
I have the following table for Customer:
```
+------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment ... | how about
```
SELECT * FROM Customer c LEFT JOIN Appointment a ON a.CustomerId = c.Id
``` | You could make two queries and `UNION` them.
```
SELECT c.first, c.last, c.id, a.id FROM appointent a
INNER JOIN customer c ON a.customer_id = c.id
UNION
SELECT c.first, c.last, c.id, null FROM customer c
```
Or an outer join, where the `a.id` would be populated with null if there was no match during th... | SELECT statement with an case statement | [
"",
"mysql",
"sql",
""
] |
Is there a way to use a where clause to check if there were zero matches between tables for a record from the first table, and produce one row or results reflecting that?
I'm trying to get results that look like this:
```
+----------+----------+-----------+----------+-------------+
| Results ... | I would suggest this:
```
SELECT
t1.Date,
t1.QueueID,
s.FromDate,
s.ToDate,
s.CampaignID
FROM
Table1 t1
LEFT JOIN
(
SELECT
t2.QueueID,
t3.FromDate,
t3.ToDate,
t3.CampaignID
FROM
Table2 t2
INNER JOIN
... | A trivial amendment to AHiggins code. Using the CTE makes it a little easier to read perhaps.
With AllDates as
(
```
SELECT
t2.QueueID,
t3.FromDate,
t3.ToDate,
t3.CampaignID
FROM Table2 t2
INNER JOIN Table3 t3 ON
t2.SPID = t3.SPID
```
)
SELECT
```
t1.Date,
t1.QueueID,
s.FromDa... | SQL Query to get results that match between three tables, or a single result for no match | [
"",
"sql",
""
] |
I have a very simple code for a cron job that makes a date entry into an SQL DB:
```
$qry_cron_test = "INSERT INTO ".$tblprefix."cron_test SET
create_datetime = '".date("Y-d-m H:i:s")."'";
$rs_cron_test = $db -> Execute($qry_cron_test);
```
The problem is the following:
Between 1st and 12th of every... | You have month and day the wrong way around.
```
$qry_cron_test = "INSERT INTO ".$tblprefix."cron_test SET
create_datetime = '".date("Y-m-d H:i:s")."'";
$rs_cron_test = $db -> Execute($qry_cron_test);
```
date("Y-**m**-**d** H:i:s") | I recommend that, unless you need milisecond information, you always store date information in [Unix Timestamp](http://www.unixtimestamp.com/). It is lighter to store, since it is only a integer value, is faster to retrieve and is universal, since it is always based on UTC.
Specially in PHP, converting date informatio... | Cron job making date database entry | [
"",
"mysql",
"sql",
"datetime",
"cron",
""
] |
I have the following problem:
I have a data table that is fed by data from a SQL query.
The query works just fine, but not all the data is displayed. I deleted one of the columns before and no wanted to readd it, but it does not show.
Is there a way to get this to work?
Basically, I have those columns:
```
Name, Fir... | I'm guessing you have Preserve column/sort/filter/layout checked in the External Data Properties dialog (right-click> Table> External Data Properties). Try unchecking it, refreshing, and then checking it again. Save first! | I had the same issue, and finally found an easy solution for adding columns. Click on the table, then Query>Edit>Advanced Editor (under the home tab).
You should see the source code for the query. In the first line of code, you will see Columns= (followed by your number of columns).
You need to change this number to ... | Excel data table (SQL query): Once deleted column no longer shows up | [
"",
"sql",
"excel",
"datatable",
""
] |
I am trying to split a single string containing multiple email address data into three variables. The strings mark the start/end of an email address with the ; character.
An example string would be:
```
'joebloggs@gmailcom;jimbowen@aol.com;dannybaker@msn.com'
```
The code I currently have for this is as follows:
``... | Assuming that there will always be 3 email addresses - the following seems to work;
```
DECLARE @Email VARCHAR(100),
@Email2 VARCHAR(100),
@Email3 VARCHAR(100)
SET @Email = 'joebloggs@gmailcom;jimbowen@aol.com;dannybaker@msn.com'
SELECT @Email = LEFT(@Email, CHARINDEX(';', @Email) - 1)
... | This solution:
```
create function dbo.SplitString
(
@str nvarchar(max),
@separator char(1)
)
returns table
AS
return (
with tokens(p, a, b) AS (
select
cast(1 as bigint),
cast(1 as bigint),
charindex(@separator, @str)
union all
select
p + 1,
b + 1,
... | Splitting an SQL string into multiple strings | [
"",
"sql",
"sql-server",
"string",
"substring",
""
] |
What I am trying to do is output (order\_id, payment\_type) together with a column title of 'Order & Payment Type Used' and (order\_date, order\_time) together with a column title of 'Date/Time'. Iv tried the below query in a number of different ways now but I always get errors.
**Query I am trying to execute**
```
S... | Escaping of special names is with ` not with '
```
SELECT CONCAT(`order_id`, ' ', `payment_type`) AS `Order & Payment Type Used`,
CONCAT(`order_date`, ' ', `order_time`) AS `Date/Time`
FROM `ORDER` ORDER BY order_id;
```
' is for strings. | Use back ticks for column and table names,quotes are for strings and dates
```
`order_id`, ' ', `payment_type`
``` | MySQL - SELECT CONCAT AS ' ' & ORDER BY - Error/Not working? | [
"",
"mysql",
"sql",
""
] |
I'm learning the way ADO.NET Models works in Entity Framework with MySQL. I Generate new test model and then select **"Generate Database from model"**
It produce for me new file "model\_name.edms.sql" - actual MySQL script for database creation.
However to execute it I have to "Connect to Server" which by default c... | I've just ran into the same problem and that's how to solve it.
I'm using VS 2010 Ultimate but I guess it's the same in VS 2013.
First, when you connect (and execute the sql) from the toolbar you actually request to do it on the **'Transact-SQL Editor' toolbar**, which means that the toolbar handles the MS databases. ... | First, you have to be sure that you have downloaded MySQL for Visual Studio. This is NOT Connector/Net (though you should probably have that, too).
In VS, when you open Server Explorer, you should be able to add a database. Input your server name, user name, password, and don't forget to click the Advanced button and ... | Visual Studio 2013 - execute Model.edmx.sql trough MySQL? | [
"",
"mysql",
"sql",
"entity-framework",
"ado.net",
"visual-studio-2013",
""
] |
I have order management system in which I have a table. There can be a request for which there should be a response. For example:-
There are 2 columns UniqueNumber and Type as below:-
```
A Request
A Response
B Request
C Request
D Request
E Request
E Response
C Response
```
I want to query those unique numbers in th... | Use a left self join with a condition that filters out matches:
```
select t1.UniqueNumber
from mytable t1
left join mytable t2 on t2.UniqueNumber = t1.UniqueNumber
and t2.type = 'Response'
where t1.type = 'Request'
and t2.type is null
```
This query works because the join condition attempts to find the response by... | You can select all Requests and the remove those that have a Response:
```
SELECT t1.UniqueNumber
FROM your_table t1
WHERE t1.Type = 'Request'
AND NOT EXISTS
(
SELECT 1
FROM your_table t2
WHERE t2.UniqueNumber = t1.UniqueNumber
AND t2.Type = 'Response'
)
```
Performance could be improved with a ... | How to query for request records that do not have response | [
"",
"sql",
"oracle",
"oracle11g",
"oracle10g",
""
] |
I have a table called `table1` in SQL Server 2008
It has the following data:
```
id refId Date IsActive
=====================================
1 2 2014-03-01 1
2 2 2014-03-01 1
3 2 2014-04-15 0 <
4 2 2014-04-15 0 <
5 ... | if you need to only include the refIds that meet your requirements, then this should work
```
select refId
from table1 as t
group by refId
having exists(
select refId
from table1 as t2
where [Date]<>'2014-04-15'
or ([Date]='2014-04-15' and IsActive=0)
group by refId
having t.refId=t2.refId
-- this ... | If this is the query in MySQL:
```
SELECT refId
FROM table1
GROUP BY refId
HAVING MAX(Date='2014-04-15') = 0 OR
MAX(Date='2014-04-15' AND IsActive=0) = 1;
```
You can readily translate this to SQL Server/ANSI SQL syntax by using the `case` statement:
```
SELECT refId
FROM table1
GROUP BY refId
HAVING MA... | Filter SQL Server records | [
"",
"sql",
"sql-server",
""
] |
I need a single query to fetch the counts based on some condition(oracle).
```
select count(*) AS TOTAL_ROWS from table
select count(*) AS TOTAL_ERROR_ROWS from table where ERROR_CODE is not null
select count(*) AS TOTAL_SUCCESS_ROWS from table where ERROR_CODE is null
```
I want to fetch all three results in 1 qu... | `SELECT TOTAL_ROWS, TOTAL_ERROR_ROWS, TOTAL_ROWS-TOTAL_ERROR_ROWS AS TOTAL_SUCCESS_ROWS
FROM (
SELECT COUNT(*) AS TOTAL_ROWS
, COUNT(ERROR_CODE) AS TOTAL_ERROR_ROWS
FROM table
) AS T` | You can use `UNION` :
```
select count(*) AS TOTAL_ROWS from table
UNION
select count(*) AS TOTAL_ROWS from table where ERROR_CODE is not null
UNION
select count(*) AS TOTAL_ROWS from table where ERROR_CODE is null
```
But it will display all three `COUNT`s in one column. To display it in three different columns... | Multiple count(*) in single query | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
HI all here is a MySQL problem that uses results from a 2 table join, conditionally assess them and outputs 2 values.
Here is the database structure.
The 1st table gtpro contains
a user ID (column name id)
a samples/year number ie 2, 4 or 12 times/year (column name labSamples\_\_yr)
The 2nd table labresults contai... | If I understand your question correctly, you should be able to put the conditions in the `where` clause:
```
SELECT a.id, a.labSamples__yr, max(b.date) as ndate
from gtpro a join
labresults b
on a.id = b.idgtpro
where (a.labSamples__yr = 2 and b.date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)) or
(a.labS... | The answer partly inspired by Tomas (sql clarification and syntax clarification) I got rid of the CASE all together. It seems nice and clean to me but I would like to hear any other suggestions
```
select id, labSamples__yr, ndate from
(SELECT a.id, a.labSamples__yr, max(b.date) as ndate from gtpro as a
join labresul... | MySQL using IF or CASE statement across joined tables | [
"",
"mysql",
"sql",
"if-statement",
"case",
""
] |
Let say I have a table:
```
ColumnA ColumnB
---------------------------------
1 10.75
4 1234.30
6 2000.99
```
How can I write a SELECT query that will result in the following:
```
ColumnA ColumnB
---------------------------------
1 10.75
2 0.00
3 ... | You can use a CTE to create a list of numbers from 1 to the maximum value in your table:
```
; with numbers as
(
select max(ColumnA) as nr
from YourTable
union all
select nr - 1
from numbers
where nr > 1
)
select nr.nr as ColumnA
, yt.Co... | Please try:
```
declare @min int, @max int
select @min=MIN(ColumnA), @max=MAX(ColumnA) from tbl
select
distinct number ColumnA,
isnull(b.ColumnB, 0) ColumnB
from
master.dbo.spt_values a left join tbl b on a.number=b.ColumnA
where number between @min and @max
``` | Select non-existing rows | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2005",
"sql-server-2008-r2",
""
] |
I'm not sure I phrased the question correctly, so feel free to correct me. Here are the tables with their data:
```
product category category_product
------- -------- ----------------
id_product id_category active id_category id_product
1 1 ... | Consider the following:
```
SELECT p.*
, COUNT(*)
, SUM(c.active = 1) active
, SUM(c.active = 0) inactive
FROM product p
JOIN category_product cp
ON cp.id_product = p.id_product
JOIN category c
ON c.id_category = cp.id_category
GROUP
BY p.id_product;
+------------+----------+------... | This way you can select product without active category.
```
SELECT p.id_product
FROM product p
WHERE NOT EXISTS
(SELECT * FROM
category_product cp
INNER JOIN category c ON c.id_category = cp.id_category
WHERE p.id_product = cp.id_product AND c.active = 1);
```
[SQL Fiddle](http://sqlfiddle... | How to select rows, which have all or none corresponding values in another table? | [
"",
"mysql",
"sql",
""
] |
I have a problem removing duplicates in a select query, while still considering the order of the rows.
I have the following example data:
```
myDate myValue
---------------------------
2014-01-01 100
2014-01-02 100
2014-01-03 200
2014-01-04 100
2014-01-05 100
2014-01-06 100
2014-01-07 300
```
I need a que... | I have not verified this, but I think this will give you what you're looking for. The inner query grabs each row, where the current value does not match the previous one. It uses `@previous` to keep track of previous row. Otherwise, it generates a `NULL` row. And finally, the outer query eliminates the `NULL` rows.
Fo... | In SQL you would use LAG or LEAD to look into the previous or next record, but MySQL doesn't support them.
So provided there is an entry for every day, you can just select the day before and compare with the current value:
```
select
mytable.mydate,
mytable.myvalue
from mytable
left outer join mytable prev on ... | MySQL "group by" maintaining the sorting of data | [
"",
"mysql",
"sql",
"group-by",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.